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