tags:

views:

333

answers:

5

Hello,

I am trying to create a textfile if it doesn't exist or append text to it if exists in vb.net.

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

And when I run the program it is writing text but how can I make it write in 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
+2  A: 

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 Then
     writer.WriteLine("Start Error Log for today")
    End If
    writer.WriteLine("Error Message in  Occured at-- " & DateTime.Now)
End Using
Espo
+1  A: 

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
Rubens Farias
Fixed for VB and to properly dispose the stream.
Joel Coehoorn
ty Joel, I was working on VB version, but yours looks much better
Rubens Farias
That doesn't write the "Start Error Log for today" message when the file is created, so it doesn't do the same as the original code would.
Guffa
fixed for you Guffa, ty
Rubens Farias
+1  A: 

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))
Else
  File.AppendAllText(strFile, "Start Error Log for today{0}Error Message in  Occured at-- {1:dd-MMM-yyyy}{0}", Environment.NewLine, Date.Today)
End If
Stevo3000
+1 (and beat me by about 40 seconds), but it's missing the new line, which is the main point of the question.
Joel Coehoorn
@Joel Coehoorn -Can we chalk it down to being Friday!
Stevo3000
+2  A: 

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 = String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
File.AppendAllText(String.Format("Error Message in  Occured at-- {0}{1}", DateTime.Now, Environment.NewLine))

Got the whole thing down to two lines of code :)

Joel Coehoorn
Yes, of course you can make the code shorter if you remove functionality. ;) You forgot the "Start Error Log for today" message that was written to the newly created file.
Guffa
+1, has the line break I missed! Tho ur first line should prob read `Dim strFile As String = String.Format("C:\ErrorLog_{0:dd-MMM-yyyy}.txt", DateTime.Today)`.
Stevo3000
Yep, it's definitely Friday
Joel Coehoorn
A: 

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 StreamWriter
Try
   If (Not File.Exists(strFile)) Then
      sw = File.CreateText(strFile)
      sw.WriteLine("Start Error Log for today")
   Else
      sw = File.AppendText(strFile)
   End If
   sw.WriteLine("Error Message in  Occured at-- " & DateTime.Now)
   sw.Close()
Catch ex As IOException
   MsgBox("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.

Guffa