C# 中Excel导入时判断是否被占用三种方法
程序员文章站
2024-02-29 12:43:40
c# 中excel导入时 判断是否被占用三种方法
excel导入时 判断是否被占用,三种方法:
1:win7可以,win10不可以
try...
c# 中excel导入时 判断是否被占用三种方法
excel导入时 判断是否被占用,三种方法:
1:win7可以,win10不可以
try { //原理,如果文件可以被移动,说明未被占用 string strpath = "c:\\123ok.excel"; string strpath2 = "c:\\123ok22.excel"; file.move(strpath, strpath2); file.move(strpath2, strpath); } catch { messagebox.show("文件被占用!"); return; }
2:文件流
try { //原理,如果文件可写,说明未被占用 system.io.filestream stream = system.io.file.openwrite("文件路径"); stream.close(); } catch { messagebox.show("文件被占用!"); return; }
3:win32 api调用(强烈推荐)
using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; using system.io; using system.runtime.interopservices; namespace windowsformsapplication1 { public partial class form1 : form { [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); public form1() { initializecomponent(); } private void button1_click(object sender, eventargs e) { try { string vfilename = @"c:\123.xlsx"; 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("没有被占用!"); } catch (exception ex) { throw ex; } } } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!