Streamwriter is cutting off my last couple of lines sometimes in the middle of a line?

Bill Blankenship picture Bill Blankenship · Oct 4, 2012 · Viewed 15.9k times · Source

Here is my code. :

FileStream fileStreamRead = new FileStream(pathAndFileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None);
FileStream fileStreamWrite = new FileStream(reProcessedFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);

                StreamWriter sw = new StreamWriter(fileStreamWrite);

                int readIndex = 0;
                using (StreamReader sr = new StreamReader(fileStreamRead))
                {
                    while (!sr.EndOfStream) {
                        Console.WriteLine("eof" + sr.EndOfStream);
                        readIndex++;
                        Console.WriteLine(readIndex);
                        string currentRecord = "";
                        currentRecord = sr.ReadLine();
                        if (currentRecord.Trim() != "")
                        {
                            Console.WriteLine("Writing " + readIndex);
                            sw.WriteLine(currentRecord);
                        }
                        else {
                            Console.WriteLine("*******************************************spaces ***********************");
                        }
                    }

It is cutting off 2 lines with one test file and half a line, and then 1 line and half a line with the other test file I am running it against.

I am not a streamreader/writer expert you can probably see.

Any ideas or suggestions would be greatly appreciated as this is driving me batty. I am sure it is me using these incorrectly.

Answer

Alexei Levenkov picture Alexei Levenkov · Oct 4, 2012

You are missing Flush/Close or simply using for your writer.

using(FileStream fileStreamWrite = 
  new FileStream(reProcessedFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
{
  using(StreamWriter sw = new StreamWriter(fileStreamWrite))
  {
   // .... write everything here
  }
}