简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM