下面是我从博客圆上拷贝的一段判断文件是否打开的代码,可是我运行了,没有效果啊!麻烦大家给看看.
无论文件是否打开,返回的结果是"没有被占用!"
using System.IO;
using System.Runtime.InteropServices;[DllImport("kernel32.dll")]
public static extern IntPtr _lopen(string lpPathName, int iReadWrite);[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr hObject);public const int OF_READWRITE = 2;
public const int OF_SHARE_DENY_NONE = 0x40;
public readonly IntPtr HFILE_ERROR = new IntPtr(-1);
private void button1_Click(object sender, EventArgs e)
{
    string vFileName = @"c:\temp\temp.bmp";
    if (!File.Exists(vFileName))
    {
        MessageBox.Show("文件都不存在,你就不要拿来耍了");
        return;
    }
    IntPtr vHandle = _lopen(vFileName, OF_READWRITE | OF_SHARE_DENY_NONE);
    if (vHandle == HFILE_ERROR)
    {
        MessageBox.Show("文件被占用!");
        return;
    }
    CloseHandle(vHandle);
    MessageBox.Show("没有被占用!");
}

解决方案 »

  1.   

    'Determine whether a file is already open or not
    Private Declare Function lOpen Lib "kernel32" Alias "_lopen" (ByVal lpPathName As String, ByVal iReadWrite As Long) As Long
    Private Declare Function lClose Lib "kernel32" Alias "_lclose" (ByVal hFile As Long) As Long
    Private Function IsFileAlreadyOpen(FileName As String) As Boolean
        Dim hFile As Long
        Dim lastErr As Long
        ' Initialize file handle and error variable.
        hFile = -1
        lastErr = 0
        ' Open for for read and exclusive sharing.
        hFile = lOpen(FileName, &H10)
        ' If we couldn't open the file, get the last error.
        If hFile = -1 Then
            lastErr = Err.LastDllError
        Else
            ' Make sure we close the file on success.
            lClose (hFile)
        End If
        ' Check for sharing violation error.
        sFileAlreadyOpen = (hFile = -1) And (lastErr = 32)
    End Function
    Private Sub Form_Load()
        'example by Matthew Gates ([email protected])
        MsgBox IsFileAlreadyOpen("c:\autoexec.bat")
    End Sub
      

  2.   

    vHandle 这个值在文件打开与不打开时是不一样的.你自己调试看一下.
      

  3.   

    有的文件是可以同时打开,如BMP,TXT,所以上面代码不能判断的,
    换成EXCEL,应该就可以判断到被占用了