我很难从 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()
method
using (FileStream stream = new FileStream(filePath, FileMode.Open))
向我抛出一个错误:
System.IO.IOException:进程无法访问该文件,因为它
正在被另一个进程使用。
I tried 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;
}
}
似乎它永远无法访问:/我不明白。