Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating and appending text to txt file in VB.NET

Tags:

vb.net

Using VB.NET, I am trying to create a text file if it doesn't exist or append text to it if exists.

For some reason, though it is creating the text file I am getting an error saying process cannot access file.

And when I run the program it is writing text, but how can I make it write on a new line?

Dim strFile As String = "C:\ErrorLog_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"  Dim sw As StreamWriter Dim fs As FileStream = Nothing  If (Not File.Exists(strFile)) Then     Try         fs = File.Create(strFile)         sw = File.AppendText(strFile)         sw.WriteLine("Start Error Log for today")      Catch ex As Exception         MsgBox("Error Creating Log File")     End Try Else     sw = File.AppendText(strFile)     sw.WriteLine("Error Message in  Occured at-- " & DateTime.Now)      sw.Close() End If 
like image 367
acadia Avatar asked Oct 23 '09 14:10

acadia


People also ask

How do I append to a text file in Visual Basic?

To append to a text fileUse the WriteAllText method, specifying the target file and string to be appended and setting the append parameter to True . This example writes the string "This is a test string." to the file named Testfile. txt .

How do I append a text file to another text file?

You do this by using the append redirection symbol, ``>>''. To append one file to the end of another, type cat, the file you want to append, then >>, then the file you want to append to, and press <Enter>.

What is append in VB net?

Appends the specified interpolated string to this instance. Append(UInt16) Appends the string representation of a specified 16-bit unsigned integer to this instance. Append(UInt32) Appends the string representation of a specified 32-bit unsigned integer to this instance.


2 Answers

Try this:

Dim strFile As String = "yourfile.txt" Dim fileExists As Boolean = File.Exists(strFile) Using sw As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))     sw.WriteLine( _         IIf(fileExists, _             "Error Message in  Occured at-- " & DateTime.Now, _             "Start Error Log for today")) End Using 
like image 142
Rubens Farias Avatar answered Oct 14 '22 05:10

Rubens Farias


Don't check File.Exists() like that. In fact, the whole thing is over-complicated. This should do what you need:

Dim strFile As String = $@"C:\ErrorLog_{DateTime.Today:dd-MMM-yyyy}.txt" File.AppendAllText(strFile, $"Error Message in  Occured at-- {DateTime.Now}{Environment.NewLine}") 

Got it all down to two lines of code :)

like image 36
Joel Coehoorn Avatar answered Oct 14 '22 05:10

Joel Coehoorn