我需要使用文本文件和List执行以下操作:
首先,如何在列表和文本文件之间进行读写?其次,如何在List中搜索字符串?最后,如何安全地从List中删除项目而不在我写的文本文件中留下空白?
public void homework()
{
string filePath = @"E:\test.txt";
string stringToAdd = "test_new";
IList readLines = new List();
// Read the file line-wise into List
using(var streamReader = new StreamReader(filePath, Encoding.Default))
{
while(!streamReader.EndOfStream)
{
readLines.Add(streamReader.ReadLine());
}
}
// If list contains stringToAdd then remove all its instances from the list; otherwise add stringToAdd to the list
if (readLines.Contains(stringToAdd))
{
readLines.Remove(stringToAdd);
}
else
{
readLines.Add(stringToAdd);
}
// Write the modified list to the file
using (var streamWriter = new StreamWriter(filePath, false, Encoding.Default))
{
foreach(string line in readLines)
{
streamWriter.WriteLine(line);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在发布问题之前尝试谷歌.
我从这里开始:
从文本文件中读取:http://dotnetperls.com/readline
写入文本文件:http://www.csharp-station.com/HowTo/ReadWriteTextFile.aspx
| 归档时间: |
|
| 查看次数: |
16868 次 |
| 最近记录: |