2

I am writing an importer in C# for an XML file. Every time I run the import I need to download the XML file from a URL.

I have wirtten the following code to download it:

var xmlPath = @"C:\Desktop\xxx.xml";
public void DownloadFile(string url, string saveAs)
{
    using(var webClient = new WebClient())
    {
        webClient.DownloadFileAsync(new Uri(url), saveAs);
    }
}

and _downloader.DownloadFile(Config.FeedUrl, xmlPath); to call the method. The Url is in the config file (Config.FeedUrl).

Then when I am trying to GetProperties(xmlPath); I get the Exception "Process Cannot access the file because the file is being used by another process.

I made sure that the destination exists but I am not sure why I get this error.

halfer
  • 19,824
  • 17
  • 99
  • 186
pinki
  • 1,388
  • 5
  • 24
  • 36
  • possible duplicate of [The process cannot access the file because it is being used by another process](http://stackoverflow.com/questions/3808540/the-process-cannot-access-the-file-because-it-is-being-used-by-another-process) – ChrisF Mar 08 '11 at 12:55

1 Answers1

6

Looks like your asynch download operation is yet to complete when you try to access the properties. Have you made sure that the download is completed before accessing the file?

You can access the file in the DownloadFileCompleted event.

http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadfilecompleted.aspx

Unmesh Kondolikar
  • 9,256
  • 4
  • 38
  • 51
  • 1
    and he probably should not dispose of the `WebClient` instance until said completion event has fired either. Looks like he should just remove the Async part of his method call and do it synchronously. – Lasse V. Karlsen Feb 28 '11 at 10:06
  • Thanks a lot both of you..The problem is resolved....I used the handler...as well as removed the async part and did run it sync.... – pinki Feb 28 '11 at 10:36
  • then you can accept the answer by clicking the tick mark below the voting arrows. :) http://meta.stackexchange.com/questions/23138/how-to-accept-the-answer-on-stack-overflow – Unmesh Kondolikar Feb 28 '11 at 11:31