Check file for write access before opening with a TextWriter

J

jtertin

I am currently using the following code to make sure a file is
writable (i.e. is not in use) by using the CanWrite method of the
FileStream object. Using the code below, the TextWriter is still
trying to write to the file and is throwing an exception (File... in
use by another process) whenever the output file (strFileName) is
open. I am trying to prevent it from writing to it at all if this is
the case... Any insight?


Public Shared Sub Log(ByVal logMessage As String)
Dim strFileName As New FileStream(strLogFile, FileMode.Append,
FileAccess.Write, FileShare.None)
If strFileName.CanWrite Then
Dim w As StreamWriter = New StreamWriter(strFileName)
w.WriteLine(DateTime.Now.ToShortDateString & vbTab &
DateTime.Now.ToLongTimeString & vbTab & logMessage)
w.Flush()
w.Close()
End If
End Sub
 
A

Alex Meleta

The CanWrite checks a possibility to write into StreamWriter.
There are couple of threads regarding files accessibility can be
helpful:

http://www.thescripts.com/forum/thread507071.html
http://www.codeproject.com/useritems/UserFileAccessRights.asp?df=100&for
umid=315432&exp=0&select=1970833

WBR, Alex Meleta

-----Original Message-----
From: jtertin [mailto:[email protected]]
Posted At: Thursday, April 05, 2007 2:54 AM
Posted To: microsoft.public.dotnet.general
Conversation: Check file for write access before opening with a
TextWriter
Subject: Check file for write access before opening with a TextWriter

I am currently using the following code to make sure a file is
writable (i.e. is not in use) by using the CanWrite method of the
FileStream object. Using the code below, the TextWriter is still
trying to write to the file and is throwing an exception (File... in
use by another process) whenever the output file (strFileName) is
open. I am trying to prevent it from writing to it at all if this is
the case... Any insight?


Public Shared Sub Log(ByVal logMessage As String)
Dim strFileName As New FileStream(strLogFile, FileMode.Append,
FileAccess.Write, FileShare.None)
If strFileName.CanWrite Then
Dim w As StreamWriter = New StreamWriter(strFileName)
w.WriteLine(DateTime.Now.ToShortDateString & vbTab &
DateTime.Now.ToLongTimeString & vbTab & logMessage)
w.Flush()
w.Close()
End If
End Sub
 

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