检查特定文件当前是否打开

时间:2012-06-15 23:06:03

标签: .net vb.net vb.net-2010

我想知道是否可以检查文件“test.txt”是否已打开?如果是,那么显示该文件正在使用的消息?我最大的问题是文件可以在记事本,word,excel等中打开。我有一些基本的编码,它检查文件是否打开 - 我要做的是检查文件当前是否打开,如果不是在使用然后进行编码,到目前为止我有以下编码。

Dim Process() As Process = System.Diagnostics.Process.GetProcessesByName("notepad")
Dim Process2() As Process = System.Diagnostics.Process.GetProcessesByName("word")

For Each p As Process In Process
    If p.MainWindowTitle.Contains("test") Then
        MessageBox.Show("file open")
    Else
        'Run my code
    End If
Next

For Each p2 As Process In Process2
    If p2.MainWindowTitle.Contains("test") Then
        MessageBox.Show("file open")
    Else
        'Run my code
    End If
Next

2 个答案:

答案 0 :(得分:1)

为什么不尝试对文件执行操作(例如,按 @ChrisW 建议打开)并检查其是否锁定:

例如

Catch ex As Exception
If TypeOf ex Is IOException AndAlso IsFileLocked(ex) Then
' do something? 
End If
End Try

Private Shared Function IsFileLocked(exception As Exception) As Boolean
    Dim errorCode As Integer = Marshal.GetHRForException(exception) And ((1 << 16) - 1)
    Return errorCode = 32 OrElse errorCode = 33
End Function

答案 1 :(得分:0)

许多应用程序在加载文件时会创建文件的临时副本。因此很难检查这一点。您可以创建一个调试器来查看哪个文件由二进制文件加载,这可能有点过分。

或者使用这样的东西:

try
{
  stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
}
catch (IOException)
{
  // the file is locked and not available to read or write.
  return true
}
finally
{
 // close the stream
}
相关问题