StreamWriter Not working in C#

3.3k views Asked by At

This piece of code worked perfectly in VS 2010. Now that I have VS 2013 it no longer writes to the file. It doesn't error or anything. (I get an alert in Notepad++ stating that the file has been updated, but there is nothing written.)

It all looks fine to me. Any Ideas?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            String line;
            try
            {
                //Pass the file path and file name to the StreamReader constructor
                StreamReader sr = new StreamReader("C:\\Temp1\\test1.txt");
                StreamWriter sw = new StreamWriter("C:\\Temp2\\test2.txt");

                //Read the first line of text
                line = sr.ReadLine();

                //Continue to read until you reach end of file
                while (line != null)
                {
                    //write the line to console window
                    Console.WriteLine(line);
                    int myVal = 3;
                    for (int i = 0; i < myVal; i++)
                    {
                        Console.WriteLine(line);
                        sw.WriteLine(line);
                    }
                    //Write to the other file
                    sw.WriteLine(line);
                    //Read the next line
                    line = sr.ReadLine();
                }

                //close the file
                sr.Close();
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}
2

There are 2 answers

3
Rahul Tripathi On BEST ANSWER

You need to Flush() the StreamWriter after write.

By default StreamWriter is buffered that means it won't output until it receives a Flush() or Close() call.

Also you can also try to close it like this:

sw.Close();  //or tw.Flush();

You can also have a look at StreamWriter.AutoFlush Property

Gets or sets a value indicating whether the StreamWriter will flush its buffer to the underlying stream after every call to StreamWriter.Write.

The other option which is now a days very popular and recommended is to use the using statement which takes care of it.

Provides a convenient syntax that ensures the correct use of IDisposable objects.

Example:

using(var sr = new StreamReader("C:\\Temp1\\test1.txt"))
using(var sw = new StreamWriter("C:\\Temp2\\test2.txt"))
{
   ...
}
3
Alexander Polyankin On

You need to close StreamWriter. Like this:

using(var sr = new StreamReader("..."))
using(var sw = new StreamWriter("..."))
{
   ...
}

This will close streams even if exception is thrown.