等到文件通过 webClient 从 URL 下载

Wait until file is downloaded from URL via webClient

我很难从 URL 下载几 MB excel 文件然后使用它。我使用的是 VS2010,所以我不能使用 await 关键字。 我的代码如下:

using (WebClient webClient = new WebClient())
                {
                    // setting Windows Authentication
                    webClient.UseDefaultCredentials = true;
                    // event fired ExcelToCsv after file is downloaded
                    webClient.DownloadFileCompleted += (sender, e) => ExcelToCsv(fileName);
                    // start download
                    webClient.DownloadFileAsync(new Uri("http://serverx/something/Export.ashx"), exportPath);
                }

ExcelToCsv()方法中的行

using (FileStream stream = new FileStream(filePath, FileMode.Open))

给我一个错误:

System.IO.IOException: The process cannot access the file because it is being used by another process.

我只在没有事件的情况下尝试了 webClient.DownloadFile(),但它抛出了同样的错误。如果我不处理也会抛出同样的错误。我能做什么?

临时解决方法可能是 Sleep() 方法,但它不是万能的。

谢谢

编辑: 我尝试了标准处理的第二种方法,但我在代码中有错误

  using (WebClient webClient = new WebClient())
                {
                    // nastaveni ze webClient ma pouzit Windows Authentication
                    webClient.UseDefaultCredentials = true;
                    // <--- I HAVE CONVERT ASYNC ERROR IN THIS LINE
                    webClient.DownloadFileCompleted += new DownloadDataCompletedEventHandler(HandleDownloadDataCompleted);

                    // spusteni stahovani
                    webClient.DownloadFile(new Uri("http://czprga2001/Logio_ZelenyKyblik/Export.ashx"), TempDirectory + PSFileName);
                }

public delegate void DownloadDataCompletedEventHandler(string fileName);
        public event DownloadDataCompletedEventHandler DownloadDataCompleted;
        static void HandleDownloadDataCompleted(string fileName)
        { 
            ExcelToCsv(fileName);
        }

编辑:方法 3 我试过这段代码

while (true)
                {
                    if (isFileLocked(downloadedFile))
                    {
                        System.Threading.Thread.Sleep(5000); //wait 5s
                        ExcelToCsv(fileName);
                        break;
                    }
                }

而且它似乎永远无法访问:/我不明白。

尝试使用 DownloadFile 而不是 DownloadFileAsync,就像您在编辑 1 中所做的那样:

string filename=Path.Combine(TempDirectory, PSFileName);
using (WebClient webClient = new WebClient())
                {
                    // nastaveni ze webClient ma pouzit Windows Authentication
                    webClient.UseDefaultCredentials = true;    
                    // spusteni stahovani
                    webClient.DownloadFile(new Uri("http://czprga2001/Logio_ZelenyKyblik/Export.ashx"), filename);
                }
ExcelToCsv(filename);  //No need to create the event handler if it is not async

从你的例子来看,你似乎不需要异步下载,所以使用同步下载并避免可能的相关问题,如here

还可以使用 Path.Combine 组合路径的各个部分,例如文件夹和文件名。

也有可能是被别的东西锁定了,用Sysinternals Process Explorer的Find DLL或Handle功能检查一下。

使用本地磁盘存储下载的文件以防止网络问题。