目前的环境:其他程序通过ftp将文件上传到本地某个目录,本地一个程序通过FileSystemWatcher类监控该目录下的created事件,一旦发现一个文件就对该文件进行处理,前期用文件复制粘贴时没有问题,但是上线后发现总是触发IOExeception提示“该文件被其他进程占用”。请问:如何能判断该文件是否被占用,如果占用就阻塞在这里,直到超时或者该文件可以方位为止?多谢:)

解决方案 »

  1.   

    前期copy没问题,FTP有问题,因为你对文件的操作没有释放
      

  2.   

    应该是FTP还在使用文件。
    FileStream fs;
    ReadFile:
    try
    {
    fs = File.OpenRead("TestFile.txt");
    }
    catch(IOException)
    {
          //文件可能被占用
    }
    好一点的方法是使用APIInstead of doing that, I would recommend declaring the CreateFile API
    function so that you can call it through the P/Invoke layer. The CreateFile
    function will return an error code if you can not access the file, which is
    much cleaner than handling the exception.Once you have that, if you are able to open the file with the CreateFile
    API, then you can pass the handle to the FileStream constructor, which takes
    a file handle.
      

  3.   

    解决方法,按照findcaiyzh的方法实现。                    while ( true ) {
                            fileHandle = CreateFileWrapper.CreateFile(e.FullPath,
                                                                      EFileAccess.GenericRead,
                                                                      EFileShare.Read,
                                                                      IntPtr.Zero,
                                                                      ECreationDisposition.OpenExisting,
                                                                      EFileAttributes.Readonly,
                                                                      IntPtr.Zero);
                            if( !fileHandle.IsInvalid ) {
                                break;
                            } else {
                                Thread.Sleep(1000);
                            }
                        }
    从这里http://pinvoke.net/default.aspx/kernel32/CreateFile.html找到CreateFile的C#封装写法。