Creating a File using StreamWriter throw exception ...

G

Guest

Hi,

My very simple application VB.NET Visual Studio 2003 console application
uses a log file to write some text to it. I am using StreamWriter object to
create and open and then append text to the log file. Now what happens is
that if i have the folder in which the stream object creates the log file
open in windows explorer, i can see that it creates the log file but then it
crashes, strnage , can somebody tell me how i can stop this from happening.
Below is the function that does it. Seems it crashes at the line where i have
********. Also this error occurs only when the log file does not exit. Once
it has created the log file and the application is restarted, then there is
no problem even if the folder is open in windows explore.

thanks,

The error message is :

"System.IO.IOException: The process cannot access the file
"C:\projects\vb.net\saga\test\sagalog.txt" because it is being used by
another process."

The function code is :

Public Function WriteToLogfile(ByVal Text As String) As String

Dim logfile As StreamWriter
Dim Logfilepath As String =
ConfigurationSettings.AppSettings("LogFilePathandName")
Dim File As File

Try

If Not File.Exists(Logfilepath) Then File.Create(Logfilepath)
*************** logfile = New StreamWriter(Logfilepath, True)
'"SAGALogfile.txt")
logfile.WriteLine(Text)
logfile.Close()

Catch ex As Exception

Finally

'logfile.Close()

End Try

End Function
 
B

Brendan Green

I can only guess that because File.Create() returns a FileStream, when you
go to write to the file, you get the IOException.

When you create a new instance of the StreamWriter class, if the specified
file name doesn't exist, it will be created. And, of course you are flagging
to append to the file if it exists (hence why it works the second time you
run it).

Hope this helps.
Cheers,
Brendan.
 
T

Truong Hong Thi

File.Create returns a FileStream. You have not yet closed it.
In fact, you can remove the whole line:
If Not File.Exists(Logfilepath) Then File.Create(Logfilepath).
The StreamWriter will create the file for you it it is not there.

Hope this helps,
Thi
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top