C#判断文件是否被占用的两种方法
方法/步骤
1、usingSystem.IO;using讵症慧鹱System.Runtime.InteropServices;[DllImport("kernel32.dll&q锇栀劐箨uot;)]publicstaticexternIntPtr_lopen(stringlpPathName,intiReadWrite);[DllImport("kernel32.dll")]publicstaticexternboolCloseHandle(IntPtrhObject);publicconstintOF_READWRITE=2;publicconstintOF_SHARE_DENY_NONE=0x40;publicreadonlyIntPtrHFILE_ERROR=newIntPtr(-1);privatevoidbutton1_Click(objectsender,EventArgse){stringvFileName=@"c:\temp\temp.bmp";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("没有被占用!");}
2、publicstaticboolIsFileInUse(stringfileName){boolinUse=true;FileStreamfs=null;try{fs=newFileStream(fileName,FileMode.Open,FileAccess.Read,FileShare.None);inUse=false;}catch{}finally{if(fs!=null)fs.Close();}returninUse;//true表示正在使用,false没有使用}