Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamWriter Not working in C#

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.");
            }
        }
    }
}
like image 247
tvoytko Avatar asked Jun 17 '15 13:06

tvoytko


People also ask

Where does StreamWriter write to?

StreamWriter. WriteLine() method writes a string to the next line to the steam. The following code snippet creates and writes different author names to the stream.

What is the difference between FileStream and StreamWriter?

Specifically, a FileStream exists to perform reads and writes to the file system. Most streams are pretty low-level in their usage, and deal with data as bytes. A StreamWriter is a wrapper for a Stream that simplifies using that stream to output plain text.

What does StreamWriter flush do?

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.


1 Answers

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.

like image 193
ranquild Avatar answered Oct 08 '22 22:10

ranquild