我有主應用程序和更新程序。我從主程序啓動更新程序,並在更新程序啓動後立即停止主程序。現在一切都好了。 現在,我從網站檢查一個xml文件,以查找必須更新的文件。 我用它來下載文件:c#無法下載文件(另一個進程使用的文件)
Stopwatch sw = new Stopwatch();
public void DownloadFile(string urlAddress, string location)
{
using (WebClient webClient = new WebClient())
{
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
Uri URL = urlAddress.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ? new Uri(urlAddress) : new Uri("http://" + urlAddress);
sw.Start();
try
{
webClient.DownloadFileAsync(URL, location);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
labelSpeed.Text = string.Format("{0} kb/s", (e.BytesReceived/1024d/sw.Elapsed.TotalSeconds).ToString("0.00"));
progressBar.Value = e.ProgressPercentage;
labelPerc.Text = e.ProgressPercentage.ToString() + "%";
downloaded.Text = string.Format("{0} MB's/{1} MB's",
(e.BytesReceived/1024d/1024d).ToString("0.00"),
(e.TotalBytesToReceive/1024d/1024d).ToString("0.00"));
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
sw.Reset();
if (e.Error != null)
{
MessageBox.Show(e.Error.InnerException.Message,e.Error.Message);
}
if (e.Cancelled == true)
{
MessageBox.Show("Download has been canceled.");
}
else
{
MessageBox.Show("Download completed!");
}
}
我呼籲使用下載方法:
foreach (string file in dld)
{
DownloadFile(file, AppDomain.CurrentDomain.BaseDirectory+file);
MessageBox.Show("done with:" + file);
}
其中,DLD是List<string> dld = new List<string>();
當我打電話的下載方法,我得到這個錯誤: "An exception occured during a WebClient request. The process cannot access the file xxx because it is used by another process."
PS:更新程序以管理員權限啓動。
我真的不明白代碼有什麼問題。我已經在這裏問過同樣的問題,但只有一個文件(通過管理員權限解決)。現在我有多個文件可供下載,即使該程序是以管理員權限啓動的,它也不起作用。我再次檢查,主程序關閉。
感謝任何幫助。
後編輯:我想我找到了問題。我有一個地方 Assembly assembly = Assembly.LoadFrom(path); Version ver = assembly.GetName().Version;
,我想這個命令鎖定文件。
現在我必須找出如何加載和卸載程序集。回到谷歌。
最後編輯:找到了解決方案,它的工作原理。 AssemblyName assembly = AssemblyName.GetAssemblyName(path); Version ver = assembly.Version;
只是爲了排除顯而易見的問題:有問題的文件是否在任何進程中同時打開? – Ben
不。這些文件只是我編譯的dll。我甚至關閉了視覺工作室......同樣的事情。 – nikodemus