编程语言
首页 > 编程语言> > C# 判断(Excel)文件是否已经打开

C# 判断(Excel)文件是否已经打开

作者:互联网

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

标签:文件,MessageBox,IntPtr,C#,Excel,int,vHandle,vFileName,public
来源: https://blog.csdn.net/LJianDong/article/details/100007769