Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to write a Text on txt File using C#

Tags:

c#

winforms

I have tried to write a string on text file,but its not writing anything and there is 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());
 }
like image 982
King_Fisher Avatar asked Dec 19 '22 01:12

King_Fisher


2 Answers

StreamWriter is IDisposable object. You should dispose it after using. For this you can use using statement like this:

    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());
    }
like image 172
Artem Kulikov Avatar answered Jan 02 '23 16:01

Artem Kulikov


Use File.AppendAllText that will do all the steps (except creating folder) for you.

Otherwise you should properly dispose writer when you are done, preferably with using in the same function:

using(oWriter)
{
  oWriter.WriteLine(DateTime.Now.ToString() + ": " + sLogInfo.Trim());
}
like image 45
Alexei Levenkov Avatar answered Jan 02 '23 15:01

Alexei Levenkov