【问题标题】:C# Using Lists to read, write and search text file linesC# 使用列表读取、写入和搜索文本文件行
【发布时间】:2010-12-19 15:08:00
【问题描述】:

我需要对一个文本文件和一个列表执行以下操作:

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

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

【问题讨论】:

  • 如果您发布您尝试过的内容,我会帮助您改正错误。

标签: c# list text


【解决方案1】:

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);
       }
    }
}

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

【讨论】:

  • 诸如“在发布问题之前尝试谷歌”之类的评论没有帮助。我曾尝试搜索此信息,但并非所有人都知道具体要搜索什么。
【解决方案2】:

【讨论】:

    【解决方案3】:

    我只是分享我的想法......

    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());
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-26
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 2016-10-06
      • 2011-05-22
      • 2012-09-15
      • 1970-01-01
      相关资源
      最近更新 更多