How to force FileSystemWatcher to wait till the file downloaded?

前端 未结 4 968
面向向阳花
面向向阳花 2021-02-08 20:11

I am downloading a file and want to execute the install only after the download is complete. How do I accomplish this? Seems like FileSystemWatcher onCreate event would do this

4条回答
  •  情深已故
    2021-02-08 20:32

    Try:

    FileInfo fInfo = new FileInfo(e.FullPath); 
    while(IsFileLocked(fInfo)){
         Thread.Sleep(500);     
    }
    InstallMSI(e.FullPath);
    
    
    static bool IsFileLocked(FileInfo file)
    {
        FileStream stream = null;
        try {
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException) {
            return true;
        }
        finally {
            if (stream != null)
                stream.Close();
        }   
        return false;
    }
    

提交回复
热议问题