DownloadFile进程无法访问该文件,因为另一个进程正在使用该文件

本文关键字:文件 进程 另一个 访问 DownloadFile 因为 | 更新日期: 2023-09-27 18:00:54

我让下载程序下载文件,它在大多数情况下运行良好,但它经常会引发异常。例外情况是:

[11:15:34 a.m.] >> [Error StartDownloadFile] An exception occurred during a WebClient request. | System.IO.IOException: The process cannot access the file 'A:'Users'user'downloads'test'file.extention' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
   at System.Net.WebClient.DownloadFile(Uri address, String fileName)

我使用的代码是:

while (true)
            {
    try
        {
            downloadUrl = new Uri(result.url);
            var fileName = dir + "''" + escapeFilename(result.passedFileName) + ".extention";
            while (true)
            {
                using (var client = new WebClient())
                {
                    client.DownloadFile(downloadUrl, fileName);
                }
                long fileSize = new FileInfo(fileName).Length;
                if (fileSize < 1000)
                {
                    Log("[Error] " + result.passedFileName + " failed, re-downloading");
                }
                else
                {
                    break;
                }
            }
            break;
        }
        catch (Exception ex)
        {
            Log("[Error StartDownloadFile] " + ex.Message + " | " + ex.InnerException);
        }
    }

现在看看其他提出类似问题的人,他们的解决方案是使用垃圾收集或类似的东西,但由于我使用的是WebClient DownloadFile,我认为这是内置的。所以我不确定是什么引发了这个异常,以及如何修复它

DownloadFile进程无法访问该文件,因为另一个进程正在使用该文件

DownloadFile((函数可能在OS//框架解锁文件之前返回。这也许可以解释为什么垃圾回收似乎可以解决这个问题:它只是延迟了对文件的访问

在这种情况下,变通办法是:

for (int i=0; i<20; i++) // time out = 20*100 ms = 2 seconds
try 
{ 
  // your code accessing to the file
  i=999 ; // exit loop 
} 
catch { system.thread.threading.Sleep(100) ; }