RyanK
RyanK

Reputation: 116

Write contents of List<string> into a text file

I have a program that checks two text files for a specific field then checks to see if either file has the specified field. If it does then the number of matches is stored into another List. The problem I am having is that it is only writing the first match to the text file, when I know I have two matches. I am fairly new to C# so any help/advice would be appreciated, the code below is doing the check.

while ((lineBeingRead = fileToRead.ReadLine()) != null)
{
    if (lineBeingRead.IndexOf("       :22:", 0) == 0)
    {
        lstTwentyOneCounter.Add(lineBeingRead.Substring(11));
        lstStoreTwentyOne = lstTwentyOneCounter;
    }
}

The code below is writing to the text file.

foreach (var single103 in lstStore103)
{
    foreach (var single101 in lstStore101)
    {
        if (single101 == single103)
        {
            checkResults.Add(single103);
            System.IO.File.WriteAllText(@"H:\Compare.txt", single103);
            break;
        }
    }
}

Thanks,
Ryan

Upvotes: 2

Views: 12408

Answers (2)

mjwills
mjwills

Reputation: 23983

WriteAllText will overwrite the existing file - so only a single entry will appear to be written.

You will want to append or write all instead.

System.IO.File.Delete(@"H:\Compare.txt");

foreach (var single103 in lstStore103)
{
    foreach (var single101 in lstStore101)
    {
        if (single101 == single103)
        {
            checkResults.Add(single103);
            System.IO.File.AppendAllText(@"H:\Compare.txt", single103 + Environment.NewLine);
        }
    }
}

or (if neither lstStore103 nor lstStore101 have duplicates):

System.IO.File.Delete(@"H:\Compare.txt");

foreach (var value in lstStore103.Intersect(lstStore101))
{
    checkResults.Add(value);
    System.IO.File.AppendAllText(@"H:\Compare.txt", value + Environment.NewLine);
}

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460288

The break; is responsible, it will leave the loop. But you also don't want to use WriteAllText which rewrites the whole text-file but you want to append a new line. I would use this approach:

string startPattern = "       :22:";
List<string> lstStoreTwentyOne = File.ReadLines(path)
    .Where(l => l.StartsWith(startPattern))
    .Select(l => l.Substring(startPattern.Length))
    .ToList();

This will create and fill the list. I don't know how this is related to the lstStore103-list.

However, this will write all to the text-file and replaces your loops:

var matchingItems = lstStore103.Intersect(lstStore101);
File.WriteAllLines(@"H:\Compare.txt", matchingItems);

Upvotes: 3

Related Questions