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; } } } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!