roostaamir
roostaamir

Reputation: 1968

cannot write strings to file using '.writeline' method of a streamwriter

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!)

Upvotes: 0

Views: 1274

Answers (3)

malix
malix

Reputation: 3572

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

Upvotes: 0

E.T.
E.T.

Reputation: 944

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");
        }

Upvotes: 1

DarkSquirrel42
DarkSquirrel42

Reputation: 10257

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

Upvotes: 3

Related Questions