Search code examples
c#streamreader

Can't find string in input file


I have a text file, which I am trying to insert a line of code into. Using my linked-lists I believe I can avoid having to take all the data out, sort it, and then make it into a new text file. What I did was come up with the code below. I set my bools, but still it is not working. I went through debugger and what it seems to be going on is that it is going through the entire list (which is about 10,000 lines) and it is not finding anything to be true, so it does not insert my code.

Why or what is wrong with this code?

List<string> lines = new List<string>(File.ReadAllLines("Students.txt"));


 using (StreamReader inFile = new StreamReader("Students.txt", true))
 {
    string newLastName = "'Constant";
    string newRecord = "(LIST (LIST 'Constant 'Malachi 'D ) '1234567890 '[email protected] 4.000000 )";
    string line;
    string lastName;
    bool insertionPointFound = false;
    for (int i = 0; i < lines.Count && !insertionPointFound; i++)
    {
        line = lines[i];
        if (line.StartsWith("(LIST (LIST "))
        {
            values = line.Split(" ".ToCharArray());
            lastName = values[2];
            if (newLastName.CompareTo(lastName) < 0)
            {
                lines.Insert(i, newRecord);
                insertionPointFound = true;
            }
        }
    }
    if (!insertionPointFound)
    {
        lines.Add(newRecord);
    }

Solution

  • You're just reading the file into memory and not committing it anywhere.

    I'm afraid that you're going to have to load and completely re-write the entire file. Files support appending, but they don't support insertions.

    you can write to a file the same way that you read from it

    string[] lines;
    /// instanciate and build `lines`
    File.WriteAllLines("path", lines);
    

    WriteAllLines also takes an IEnumerable, so you can past a List of string into there if you want.


    one more issue: it appears as though you're reading your file twice. one with ReadAllLines and another with your StreamReader.