Search code examples
c#streamwriter

How do I write to a .cs file in c# and/or how to change the .txt to .cs


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.


Solution

  • 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.