sls@cnicorp.com
Member
- Joined
- Dec 28, 2004
- Messages
- 7
- Programming Experience
- 5-10
I am using VS2005 VB and running into a problem that my program is processing files while they are still in use.
The principle is correct but don't use a StreamReader. A StreamReader is for reading text from a stream. If you don't want to read text then it serves no purpose. You may as well just create the stream directly because the StreamReader will create a FileStream under the hood anyway.The only way to know if a file is open is to try to open it yourself with exclusive access. Look into the System.IO.StreamReader class and try to open your file with read-only exclusive access.
private bool FileInUse(string filename)
{
// If the file can be opened for exclusive access it means that the file
// is no longer locked by another process.
try {
using (FileStream f = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None)) {
return false;
}
} catch (FileNotFoundException fnfe) {
throw fnfe;
} catch (IOException) {
return true;
}
}
That works too, I simply suggest to people to use a StreamReader because usually they're already familiar with using it, and having open the file exclusively will still throw the exception if the file's in use.here's a scrap of C# I use for this very purpose:
VB.NET:private bool FileInUse(string filename) { // If the file can be opened for exclusive access it means that the file // is no longer locked by another process. try { using (FileStream f = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None)) { return false; } } catch (FileNotFoundException fnfe) { throw fnfe; } catch (IOException) { return true; } }
Function IsFileAvailable(ByVal theDocument As String) As Boolean
Try
File.Open(theDocument, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
IsFileAvailable = True
Catch
IsFileAvailable = False
' Display whatever message appropriate
End Try
End Function