日期:2014-05-18  浏览次数:20764 次

关于判断文件是否打开的代码
下面是我从博客圆上拷贝的一段判断文件是否打开的代码,可是我运行了,没有效果啊!麻烦大家给看看.
无论文件是否打开,返回的结果是"没有被占用!"

C# code

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("没有被占用!");
}




------解决方案--------------------
'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 (Puff0rz@hotmail.com)
MsgBox IsFileAlreadyOpen("c:\autoexec.bat")
End Sub

------解决方案--------------------
vHandle 这个值在文件打开与不打开时是不一样的.你自己调试看一下.
------解决方案--------------------
顶了