简体   繁体   中英

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

I need to perform the following operations with a text file and a List:

  1. Read all lines of text file (non delimited) into a string based list
  2. Whilst the application is open I need to do the following:
    • Check for instances of a string in the List
    • Add new entries to the List
    • Remove all identical instances of a defined string from the List
  3. Write the contents of the List back to the text file including any changes made as soon as they are made

Firstly, how do I read and write between Lists and text files? Secondly, how do I search a List for a string? Lastly, how do I safely remove an item out of a List without leaving gaps in the text file I write?


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

Try to google before you post the question.

I'll just share my idea...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM