簡體   English   中英

C#使用列表來讀取,寫入和搜索文本文件行

[英]C# Using Lists to read, write and search text file lines

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

  1. 將所有文本文件行(非分隔)讀入基於字符串的列表
  2. 應用程序打開時,我需要執行以下操作:
    • 檢查列表中字符串的實例
    • 向列表添加新條目
    • 從List中刪除已定義字符串的所有相同實例
  3. 將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);
       }
    }
}

在發布問題之前嘗試谷歌。

我從這里開始:

從文本文件中讀取: http//dotnetperls.com/readline

列表操作
1. 從列表中刪除
2. 在列表中搜索

寫入文本文件: http//www.csharp-station.com/HowTo/ReadWriteTextFile.aspx

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM