Destination file blank after writing with StreamWriter C#

I have written a console application that in itself is working as I would like it to. It's main output works great in console. But the results inside the loop I want written to a text file. I have used StreamWriter to attempt this and although I receive no errors on compilation or running, the file in my C: drive remains blank. Can anyone spot any stupid or quick things I have missed?

If you can help, thank you in advance.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test2
{
    class Program
    {
        static void Main(string[] args)
        {
            System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\Test.txt");
            double z = 0;
            double x = 1;
            double y = 1;

            Console.WriteLine("How many lines should be written to the file?");
            Console.WriteLine();
            z = double.Parse(System.Console.ReadLine());

            Console.WriteLine("Writing " + z + "lines to file!");
            Console.WriteLine();

            while (z > 0)
            {
                y = Math.Pow(x, 2);
                Console.WriteLine(x + ", " + y*10);
                file.WriteLine(x + ", " + y*10);
                z = z - 1;
                x = x + 1;

            }
            Console.WriteLine();
            Console.WriteLine("**Generation Complete**");
            Console.WriteLine();
            Console.WriteLine("-------------------------------");
            Console.WriteLine();
            Console.WriteLine("**Writing to file successful**");
            Console.WriteLine();
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();

            file.Close();

        }
    }
}
Jon Skeet
people
quotationmark

When I run that code, I see an exception:

Unhandled Exception: System.UnauthorizedAccessException:
Access to the path 'c:\Test.txt' is denied.

It's not clear how you're running this, but if it's configured as a console app and you run it from a console window so you'll definitely see any exceptions, I suspect you'll see the same thing.

Try changing it to write to somewhere you definitely have access to - and also try to work out why you didn't see the exception before.

Additionally it would definitely be better to use a using statement as other answers have shown - but that wouldn't explain a clean run (no exceptions) without the file being created.

people

See more on this question at Stackoverflow