King_Fisher
King_Fisher

Reputation: 1203

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

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

Upvotes: 4

Views: 268

Answers (4)

Artem Kulikov
Artem Kulikov

Reputation: 2296

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

Upvotes: 6

Joel Legaspi Enriquez
Joel Legaspi Enriquez

Reputation: 1236

You should flush (disposing is enough) your data into the 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 mentioned looking at C#'s StreamWriter.cs class it does indeed calls the Flush method internally. See here: Reference

Upvotes: 1

Zachi Shtain
Zachi Shtain

Reputation: 836

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

Upvotes: 2

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

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

Upvotes: 2

Related Questions