我需要使用文本文件和List执行以下操作:
首先,如何在列表和文本文件之间进行读写? 其次,如何在List中搜索字符串? 最后,如何安全地从List中删除项目而不在我写的文本文件中留下空白?
答案 0 :(得分:8)
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);
}
}
}
在发布问题之前尝试谷歌。
答案 1 :(得分:7)
我从这里开始:
从文本文件中读取:http://dotnetperls.com/readline
List Actions
1. Removing from a list
2. Searching in a List
写入文字文件:http://www.csharp-station.com/HowTo/ReadWriteTextFile.aspx
答案 2 :(得分:1)
我只是分享我的想法......
using System.IO;
public void newMethod()
{
//get path of the textfile
string textToEdit = @"D:\textfile.txt";
//read all lines of text
List<string> allLines = File.ReadAllLines(textToEdit).ToList();
//from Devendra's answer
if (allLines.Contains(stringToAdd))
{
allLines.Remove(stringToAdd);
}
else
{
allLines.Add(stringToAdd);
}
//extra: get index and edit
int i = allLines.FindIndex(stringToEdit => stringToEdit.Contains("need to edit")) ;
allLines[i] = "edit";
//save all lines
File.WriteAllLines(textToEdit, allLines.ToArray());
}