0

I wrote some code, which should write to file some text:

        private static FileStream CreateFile()
        {
            string _fileName = "znaki.txt";

            if(File.Exists(_fileName))
            {
                File.Delete(_fileName);
            }

            FileStream fs = new FileStream(_fileName, FileMode.Create, FileAccess.Write);

            Console.Clear();
            Console.Write("Ile znakok chcesz wygenerowac? >> ");
            int lp;
            lp = Convert.ToInt32(Console.ReadLine());

            Random r = new Random();
            StreamWriter sw = new StreamWriter(fs);
            for (int i = 0; i < lp; i++)
            {
                Console.Clear();
                Console.WriteLine(i + "/" + lp);

                sw.WriteLine("jogurcik");
            }

            return fs;
        }

This code create the file but don't write anything. What is wrong with this code?

1 Answers1

2

Close StreamWriter (as well as FileStream) at the end of the writing routine:

sw.Close();
fs.Close();

MSDN:

You must call Close to ensure that all data is correctly written out to the underlying stream... Flushing the stream will not flush its underlying encoder unless you explicitly call Flush or Close.

P.S. Alternative way is to use the using statement that helps to close and dispose of IO objects automatically:

using (FileStream fs = new FileStream(_fileName, FileMode.Create, FileAccess.Write))
{
    ...
    using (StreamWriter sw = new StreamWriter(fs)) 
    { 
        for (int i = 0; i < lp; i++)
        {
            ...
            sw.WriteLine("jogurcik");
        }
    }
}

In this case you can ommit the close call.

user2316116
  • 6,485
  • 1
  • 19
  • 34