我们在操作配置文件的时候,或者是导出一些文件的时候,这个文件是被占用状态,此时无法对文件做其它操作,那么我想等这个文件被其它操作的占用解除后,再对其进行操作,我该如何知道这个文件是否能被操作呢?效果图在文章最后。1、首先我们需要对该文件是否被占用做一个判断,来看下面这个函数summary返回指示文件是否已被其它程序使用的布尔值summaryparamnamefileFullName文件的完全限定名,例如:C:MyFile。txt。paramreturns如果文件已被其它程序使用,则为否则为false。returnspublicBooleanGOFileIsUsed(StringfileFullName){B判断文件是否存在,如果不存在,直接返回falseif(!System。IO。File。Exists(fileFullName)){}else{看看文件是否能用程序打开。System。IO。FileStreamfileStry{fileStreamSystem。IO。File。Open(fileFullName,System。IO。FileMode。Open,System。IO。FileAccess。ReadWrite,System。IO。FileShare。None);能正常打开}catch(System。IO。IOExceptionioEx){出错说明不能打开,返回true,正在被占用}catch(System。Exceptionex){}finally{if(fileStream!null){fileStream。Close();}}}}2、我们在另一个线程中随时判断这个文件是否被占用,等到占用解除时再做其它操作usingSusingSystem。TusingSystem。Windows。Fnamespacetest{publicpartialclassForm1:Form{publicForm1(){InitializeComponent();}privatevoidForm1Load(objectsender,EventArgse){让线程能够操作button的值,省着用委托CheckForIllegalCrossThreadCtimer开始判断timer1。Start();}privatevoidtimer1Tick(objectsender,EventArgse){每隔一小段时间去检查一下这个文件是否被占用ThreadthreadnewThread(Go);thread。Start();}privatevoidbutton1Click(objectsender,EventArgse){}voidGo(){if(GOFileIsUsed(D:1a。docx)){button1。Text正在被占用;}else{button1。Text未被占用;没有被占用的话,就可以做其它事了。。。}}publicBooleanGOFileIsUsed(StringfileFullName){B判断文件是否存在,如果不存在,直接返回falseif(!System。IO。File。Exists(fileFullName)){}else{看看文件是否能用程序打开。System。IO。FileStreamfileStry{fileStreamSystem。IO。File。Open(fileFullName,System。IO。FileMode。Open,System。IO。FileAccess。ReadWrite,System。IO。FileShare。None);能正常打开}catch(System。IO。IOExceptionioEx){出错说明不能打开,返回true,正在被占用}catch(System。Exceptionex){}finally{if(fileStream!null){fileStream。Close();}}}}}}也可以直接在线程中等待usingSusingSystem。TusingSystem。Windows。Fnamespacetest{publicpartialclassForm1:Form{publicForm1(){InitializeComponent();}boolOKprivatevoidForm1Load(objectsender,EventArgse){让线程能够操作button的值,省着用委托CheckForIllegalCrossThreadCThreadthreadnewThread(Go);thread。Start();}privatevoidbutton1Click(objectsender,EventArgse){}voidGo(){while(true){if(GOFileIsUsed(D:1a。docx)){button1。Text正在被占用;}else{OKbutton1。Text未被占用;}}}publicBooleanGOFileIsUsed(StringfileFullName){B判断文件是否存在,如果不存在,直接返回falseif(!System。IO。File。Exists(fileFullName)){}else{看看文件是否能用程序打开。System。IO。FileStreamfileStry{fileStreamSystem。IO。File。Open(fileFullName,System。IO。FileMode。Open,System。IO。FileAccess。ReadWrite,System。IO。FileShare。None);能正常打开}catch(System。IO。IOExceptionioEx){出错说明不能打开,返回true,正在被占用}catch(System。Exceptionex){}finally{if(fileStream!null){fileStream。Close();}}}}}}真正的应用场景,可以在让这个窗体做为一个等待窗体showdialog(),然后文件解除占用后,关闭这个窗体,就可以继续往下操作了。