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 StreamWriterDim fs As FileStream = NothingIf (Not File.Exists(strFile)) ThenTryfs = File.Create(strFile)sw = File.AppendText(strFile)sw.WriteLine("Start Error Log for today")Catch ex As ExceptionMsgBox("Error Creating Log File")End TryElsesw = File.AppendText(strFile)sw.WriteLine("Error Message in Occured at-- " & DateTime.Now)sw.Close()End If
Best Answer
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
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 :)
This should work for you without changing program logic (by not outputting "Start error" on the top of each file) like the other answers do :)Remember to add exception handling code.
Dim filePath As String = String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))Dim fileExists As Boolean = File.Exists(filePath)Using writer As New StreamWriter(filePath, True)If Not fileExists Thenwriter.WriteLine("Start Error Log for today")End Ifwriter.WriteLine("Error Message in Occured at-- " & DateTime.Now)End Using
You didn't close the file after creating it, so when you write to it, it's in use by yourself. The Create method opens the file and returns a FileStream object. You either write to the file using the FileStream or close it before writing to it. I would suggest that you use the CreateText method instead in this case, as it returns a StreamWriter.
You also forgot to close the StreamWriter in the case where the file didn't exist, so it would most likely still be locked when you would try to write to it the next time. And you forgot to write the error message to the file if it didn't exist.
Dim strFile As String = "C:\ErrorLog_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"Dim sw As StreamWriterTryIf (Not File.Exists(strFile)) Thensw = File.CreateText(strFile)sw.WriteLine("Start Error Log for today")Elsesw = File.AppendText(strFile)End Ifsw.WriteLine("Error Message in Occured at-- " & DateTime.Now)sw.Close()Catch ex As IOExceptionMsgBox("Error writing to log file.")End Try
Note: When you catch exceptions, don't catch the base class Exception, catch only the ones that are releveant. In this case it would be the ones inheriting from IOException.
Why not just use the following simple call (with any exception handling added)?
File.AppendAllText(strFile, "Start Error Log for today")
EDITED ANSWER
This should answer the question fully!
If File.Exists(strFile)File.AppendAllText(strFile, String.Format("Error Message in Occured at-- {0:dd-MMM-yyyy}{1}", Date.Today, Environment.NewLine))ElseFile.AppendAllText(strFile, "Start Error Log for today{0}Error Message in Occured at-- {1:dd-MMM-yyyy}{0}", Environment.NewLine, Date.Today)End If
While I realize this is an older thread, I noticed the if block above is out of place with using:
Following is corrected:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.ClickDim filePath As String =String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))Using writer As New StreamWriter(filePath, True)If File.Exists(filePath) Thenwriter.WriteLine("Error Message in Occured at-- " & DateTime.Now)Elsewriter.WriteLine("Start Error Log for today")End IfEnd UsingEnd Sub
Try it this way:
Dim filePath As String = String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))if File.Exists(filePath) thenUsing writer As New StreamWriter(filePath, True)writer.WriteLine("Error Message in Occured at-- " & DateTime.Now)Elsewriter.WriteLine("Start Error Log for today")End Usingend if
If File.Exists(filePath) ThenUsing writer As New StreamWriter(filePath, True)writer.WriteLine(message & " - " & DateTime.Now)End UsingElseUsing writer As New StreamWriter(filePath, True)writer.WriteLine("SUSHI Bot Event LOG: Started" & " - " & DateTime.Now)End UsingEnd If