Unable to write text on txt file using C #

I tried to write a line in a text file, but wrote nothing and there are no exceptions. My code is:

public void CreateLog(string sLogInfo) { string sDestionation = null; string sFileName = DateTime.Now.ToString("yyyyMMdd") + "_log.txt"; sDestionation = @"D:\Log\"; //sDestionation = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + ConfigurationManager.AppSettings["DestinationPath"].ToString(); string sFile = sDestionation + sFileName; if (!System.IO.Directory.Exists(sDestionation)) { System.IO.Directory.CreateDirectory(sDestionation); } StreamWriter oWriter = null; if (!System.IO.File.Exists(sFile)) { oWriter = File.CreateText(sFile); } else { oWriter = File.AppendText(sFile); } oWriter.WriteLine(DateTime.Now.ToString() + ": " + sLogInfo.Trim()); } 
+4
source share
4 answers

StreamWriter is an IDisposable object. You must dispose of it after use. For this you can use using :

  public void CreateLog(string sLogInfo) { string sDestionation = null; string sFileName = DateTime.Now.ToString("yyyyMMdd") + "_log.txt"; sDestionation = @"D:\Log\"; var sFile = sDestionation + sFileName; if (!Directory.Exists(sDestionation)) { Directory.CreateDirectory(sDestionation); } using (var oWriter = new StreamWriter(sFile, true)) oWriter.WriteLine(DateTime.Now + ": " + sLogInfo.Trim()); } 
+6
source

Use File.AppendAllText , which will follow all the steps (except creating a folder) for you.

Otherwise, you must delete the entry correctly when you are done, preferably using using in the same function:

 using(oWriter) { oWriter.WriteLine(DateTime.Now.ToString() + ": " + sLogInfo.Trim()); } 
+2
source

Your code looks great, however, I think you should add at the end of the following: oWriter.Close()

+2
source

You need to flush (place enough) your data into a file at the end of your code: oWriter.Flush(); //Save (Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.)

 oWriter.Dispose(); //Then free this resource 

As Yuval said, looking at the C # StreamWriter.cs class, he really calls the Flush method inside. See Here: Reference

+1
source

All Articles