Thursday, March 13, 2014

.NET Function to check if a file in use

Here is a .NET Function to use whether a file in system is in use by another process or application before attempting to use the file.

If the file is in use following function will return false.

VB.NET

  1. Public Function FileInUse(ByVal sFile As String) As Boolean
  2. Dim thisFileInUse As Boolean = False
  3. If System.IO.File.Exists(sFile) Then
  4. Try
  5. Using f As New IO.FileStream(sFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
  6. ' thisFileInUse = False
  7. End Using
  8. Catch
  9. thisFileInUse = True
  10. End Try
  11. End If
  12. Return thisFileInUse
  13. End Function

C#

  1. public bool FileInUse(string sFile)
  2. {
  3. bool thisFileInUse = false;
  4. if (System.IO.File.Exists(sFile)) {
  5. try {
  6. using (System.IO.FileStream f = new System.IO.FileStream(sFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) {
  7. // thisFileInUse = False
  8. }
  9. } catch {
  10. thisFileInUse = true;
  11. }
  12. }
  13. return thisFileInUse;
  14. }

No comments: