behi behi
behi behi

Reputation: 137

Why StreamWriter can't write text into file in c#?

I'm new in c#, and I'm writing a some text into a file, for this purpose, I'm using a source code which I found searching on Google:

FileStream fs = System.IO.File.OpenWrite(Server.MapPath("~/FILE/") + logFile);
StreamWriter sw = new StreamWriter(fs);

//sw.Write(DateTime.Now.ToString() + " sent email to " + email);
sw.Write(" sent email to " );

fs.Close();

This code runs, but when I open text file, I can't see any data in it, what is happening? How can I solve this problem?

Upvotes: 1

Views: 967

Answers (2)

Uthistran Selvaraj
Uthistran Selvaraj

Reputation: 1371

Modified your code as below. hope you are looking for this kind.

 using (FileStream fs = System.IO.File.OpenWrite(Server.MapPath("~/FILE/") + logFile))
 {
    using (StreamWriter sw = new StreamWriter(fs))
    {
        //sw.Write(DateTime.Now.ToString() + " sent email to " + email);
        sw.Write(" sent email to ");
    }
    fs.Close();
 }

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Try simple File.AppendAllText

File.AppendAllText(Path.Combine(Server.MapPath("~/FILE/"), logFile),
  string.Format("{0} sent email to {1}", DateTime.Now, email)); 

to append the log file instead using streams and writers.

Upvotes: 0

Related Questions