0

I want to write a simple string in a text file using the stream writer class,But it doesn't seem to work(and there are no errors).here's my code:

StreamWriter test = new StreamWriter("mytext.txt", true);

// used the below code too to create the file. It didn't work either!
//StreamWriter test = File.CreateText("mytext.txt"); 
test.WriteLine("hello");

when I run this code,nothing will be added to the text file!Where did I go wrong?(ps:I used the full path file names too!but it didn't work!)

3 Answers 3

3
using(StreamWriter test = new StreamWriter("mytext.txt", true)){
        test.WriteLine("hello");
}

problem is that the buffer of your stream is not flushed ... you could either call flush() or make sure it is properly disposed by the using block ...

Sign up to request clarification or add additional context in comments.

2 Comments

the problem is that I don't want to write to my file right after I created it!I can't use the 'using block' because my work with the file goes outside of the 'using block'.And if I try 'text.Flush()' at hte end of my code,it will face an error saying that the file is being used by another process.what to do now?
you didn't show the code for that problem ... if you want to keep the stream open, ok ... but the error you are getting suggests that you open two or more streams to the same file at the same time, or that you don't dispose the first one properly
1

You have to close the connection in order to write to the file.
Best practice is simply using using.

There is no problem in updating a file after creating it. But you must always take care of the stream.

        using (StreamWriter test = new StreamWriter("mytext.txt", true))
        {
            test.WriteLine("File created");
        }

        //Do Stuff...

        using (StreamWriter test = new StreamWriter("mytext.txt", true))
        {
            test.WriteLine("hello");
        }

Comments

0

Do you have the file open in another program like notepad++?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.