C# 中Excel导入时判断是否被占用三种方法
C#中Excel导入时判断是否被占用三种方法
Excel导入时判断是否被占用,三种方法:
1:Win7可以,WIN10不可以
try
{
//原理,如果文件可以被移动,说明未被占用
stringstrPath="C:\\123OK.Excel";
stringstrPath2="C:\\123OK22.Excel";
File.Move(strPath,strPath2);
File.Move(strPath2,strPath);
}
catch
{
MessageBox.Show("文件被占用!");
return;
}
2:文件流
try
{
//原理,如果文件可写,说明未被占用
System.IO.FileStreamstream=System.IO.File.OpenWrite("文件路径");
stream.Close();
}
catch
{
MessageBox.Show("文件被占用!");
return;
}
3:WIN32API调用(强烈推荐)
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.IO;
usingSystem.Runtime.InteropServices;
namespaceWindowsFormsApplication1
{
publicpartialclassForm1:Form
{
[DllImport("kernel32.dll")]
publicstaticexternIntPtr_lopen(stringlpPathName,intiReadWrite);
[DllImport("kernel32.dll")]
publicstaticexternboolCloseHandle(IntPtrhObject);
publicconstintOF_READWRITE=2;
publicconstintOF_SHARE_DENY_NONE=0x40;
publicreadonlyIntPtrHFILE_ERROR=newIntPtr(-1);
publicForm1()
{
InitializeComponent();
}
privatevoidbutton1_Click(objectsender,EventArgse)
{
try
{
stringvFileName=@"c:\123.xlsx";
if(!File.Exists(vFileName))
{
MessageBox.Show("文件都不存在!");
return;
}
IntPtrvHandle=_lopen(vFileName,OF_READWRITE|OF_SHARE_DENY_NONE);
if(vHandle==HFILE_ERROR)
{
MessageBox.Show("文件被占用!");
return;
}
CloseHandle(vHandle);
MessageBox.Show("没有被占用!");
}
catch(Exceptionex)
{
throwex;
}
}
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下