Archived Content: This information is no longer maintained and is provided "as is" for your convenience.
Summary
Sometimes it’s good to report errors to a log file (outside of the built-in TRIM error reporting). There are a few easy ways to do this using the Microsoft Scripting Runtime in VB6 and the System.IO in C#.
Reference
Return to SDK Samples
Reading, Writing, & Creating a Text File
Sometimes it’s good to report errors to a log file (outside of the built-in TRIM error reporting). There are a few easy ways to do this using the Microsoft Scripting Runtime in VB6 and the System.IO in C#.
In VB:
Creating and Writing a text file:
Private Sub CreateTextFile(ByVal FileName As String, ByVal Text As String) Dim FS As New FileSystemObject Dim Stream As TextStream If Not FS.FileExists(FileName) Then Call FS.CreateTextFile(FileName, True) Set Stream = FS.OpenTextFile( _ FileName, ForWriting, False) Call Stream.Write(Text) Stream.Close End If Set FS = NothingEnd Sub
Reading text from a text file:
Private Function ReadTextFile(ByVal FileName As String) As String Dim FS As New FileSystemObject Dim Stream As TextStream If FS.FileExists(FileName) Then Set Stream = FS.OpenTextFile( _ FileName, ForReading) ReadTextFile = Stream.ReadAll Stream.Close End If Set FS = NothingEnd Function
In C#:
Creating and Writing a text file:
private void WriteTextFile(string Text, string FileName) { TextWriter tw = new StreamWriter(FileName); tw.WriteLine(Text); tw.Close(); }
Reading a text file:
private string ReadTextFile(string FileName) { string returnText; try { TextReader tr = new StreamReader(FileName); returnText = tr.ReadToEnd(); tr.Close(); return returnText; } catch { returnText = ""; return returnText; } }