Sarah
Sarah

Reputation: 21

C# writing to file issue

Im trying to load some stuff from a text file, do some processing and write them to a new text file in C#.

Please have a look at my code below:

Everything seems to be working fine, I can load the stuff, edit them and save them into the text file. however, in the middle of saving them it just stops saving them into the text file for some reason, the while loop runs, I can know this because I'm also logging stuff in the console, and everything's fine in there. but after some point (like 80 lines or something), it just stops adding the new lines to the file.

Any idea?

Thanks in advance

        StreamReader SR;
        StreamWriter SW;
        string S;
        double temp1;
        double temp2;

        SR = File.OpenText("C:\...Address");
        SW = File.CreateText("C:\...Address");            

        S = SR.ReadLine();

        while (S!=null)
        {

            string[] words = S.Split(' ');

            //editing stuff

            SW.WriteLine("{0} {1} {2}", temp1, temp2, words[2]);
            Console.WriteLine("{0} {1} {2}", temp1, temp2, words[2]);
            S= SR.ReadLine();
        }

Upvotes: 2

Views: 209

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503889

Two possible issues:

  • It's not clear whether there's one file involved or two. You'll find it tricky to read from the same file you're writing to
  • You're not closing the writer, which means it won't get flushed. That may well be the issue - it would certainly explain the symptoms.

The second bullet is best handled with a using statement:

using (TextWriter writer = File.CreateText(...))
{
    // Code here
} // writer will automatically be disposed here

You should do the same thing for the reader as well. It's less important in terms of data loss, but in general you should dispose anything which implements IDisposable, typically to allow resources to be cleaned up deterministically.

Upvotes: 4

Related Questions