KnowDotNet NetRefactor

Use FileStream and StreamWriter to Write One File A Day

Let the .NET FrameWork Do The Logic

by Les Smith
Print this Article Discuss in Forums

Ever have the need to create only one file, of any type, per day, like a daily log?  If you scratched your head to figure the logic or used File.Exists(), read this article.

The .NET Framework brings so much richness to the development experience.  One of these things is the power of IO Namespace.  It does so much for you that you had to do a lot of twisting and turning to do in earlier versions of VB.NET or C (before C#).  

I am often faced with having to create a log file from an application that runs multiple times in a day and I want to create only one file per 24 hour day.  With FileStream class, I can do this practically no thought.  The WriteToFile method, shown below, will do that.  

   Private Sub Write2File(ByVal msg As String, ByVal filePath As String)
      
Dim fs As FileStream = New FileStream(filePath, FileMode.Append)
      
Dim sw As StreamWriter = New StreamWriter(fs)
      sw.WriteLine(msg)
      sw.Flush()
      sw.Close()
      fs.Close()
  
End Sub

Since the Open Mode of the FileStream constructor is FileMode.Append, if the specified
filePath (complete path and filename) and file already exist, it will be appended to.  Otherwise, a new file is created automatically.

The C# version of the code is shown below.

   private void Write2File(string msg, string filePath)
   {
      FileStream fs =
new FileStream(filePath, FileMode.Append);
      StreamWriter sw =
new StreamWriter(fs);
      sw.WriteLine(msg);
      sw.Flush();
      sw.Close();
      fs.Close();
   }

I realize that this is not rocket science and most of you have not learned anything, but maybe it will be a new trick to add to someone's code trick bag.


If you have any comments or suggestions on this article or any other programming subject you would like to discuss, comment on my blog at Click Here.

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing