1

Can someone point me what's wrong with this code? I am simply trying to write to a file, but nothing gets written to the file. Sorry this is a stupid question.. File gets created but nothing is written on to it.

public static void Main(string[] args) {
    StreamWriter writer = new StreamWriter(@"C:\File\Test.txt");
    writer.WriteLine("Fun Times!");
    Console.WriteLine("Finally !");
    Console.ReadLine();
}
2

3 Answers 3

4

You're not closing the file. One way to do this is to wrap your writer in a using statement:

using(StreamWriter writer = new StreamWriter(@"C:\File\Test.txt"))
{
    writer.WriteLine("Fun Times!");
}

Console.WriteLine("Finally !");
Console.ReadLine();
Sign up to request clarification or add additional context in comments.

Comments

3

You have to Close the StreamWriter writer.Close();

1 Comment

Of course you also can use using, this ensures that the object is always disposed correctly
0

You can also try:

System.IO.File.WriteAllText("YourPathTpoFile","TheTextShouldBeWrittenInFile");

Have a look at its documentation too.

Also, If you have text in an array then you can write using WriteAllLines:

System.IO.File.WriteAllLines("YourPathTpoFile", stringArrayOfLines);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.