-2

I want to write to a .cs file in C#. This is the (very basic) code I'm using:

StreamWriter file = new StreamWriter ("test.cs");   
file.WriteLine ("Console.WriteLine(\"It worked\")");

It successfully creates the file, but doesn't write anything to it.

Also, I was wondering if it's possible to change from .txt to .cs in any way?

To the person who said that this was a duplicate: The reason this is not a duplicate is that it is talking about writing to a .cs file, not a .txt which is what the other question talks about.

Nic
  • 6,211
  • 10
  • 46
  • 69
Mindstormer
  • 299
  • 3
  • 16
  • From what you have, it looks like it already is a `.cs` file. Also, please let me know if my clarification of how it's not working is incorrect -- I guessed. – Nic Nov 25 '15 at 01:33
  • It creates the .cs file but fails to actually write any strings to the file. – Mindstormer Nov 25 '15 at 03:25
  • Please don't tag questions with [finished] or [answered]. Clicking the check mark does that for you. – Nic Jan 12 '16 at 17:24

1 Answers1

4

You're not flushing the stream, so it's not writing to the file.

There's a few ways to do it. Call Flush after the write, or set AutoFlush = true... or just surround it all with a using statement like this:

using (StreamWriter file = new StreamWriter ("test.cs"))
{
    file.WriteLine("Console.WriteLine(\"It worked\")");
}

As for the file extension, you're already specifying "test.cs", so that should be fine.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • Thank you so much for helping me. I thought this might have been a duplicate but I had searched for about 2 days with no success on figuring this out. – Mindstormer Nov 25 '15 at 03:25