Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

text

list

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?

like image 225
SystemX17 Avatar asked Dec 19 '10 15:12

SystemX17


2 Answers

I'd start here:

Read from text file: http://dotnetperls.com/readline

List Actions
1. Removing from a list
2. Searching in a List

Write to a text file: http://www.csharp-station.com/HowTo/ReadWriteTextFile.aspx

like image 35
kemiller2002 Avatar answered Oct 16 '22 07:10

kemiller2002



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.

like image 51
Devendra D. Chavan Avatar answered Oct 16 '22 06:10

Devendra D. Chavan