C#使用列表来读取,写入和搜索文本文件行

Sys*_*X17 5 c# text list

我需要使用文本文件和List执行以下操作:

  1. 将所有文本文件行(非分隔)读入基于字符串的列表
  2. 应用程序打开时,我需要执行以下操作:
    • 检查列表中字符串的实例
    • 向列表添加新条目
    • 从List中删除已定义字符串的所有相同实例
  3. 将List的内容写回文本文件,包括所做的任何更改

首先,如何在列表和文本文件之间进行读写?其次,如何在List中搜索字符串?最后,如何安全地从List中删除项目而不在我写的文本文件中留下空白?

Dev*_*van 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);
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

在发布问题之前尝试谷歌.

  • 像"在发布问题之前尝试谷歌"这样的评论没有帮助.我曾尝试搜索此信息,但并非所有人都知道具体要搜索的内容. (10认同)