0

I'm new to WinForms/C#/VB.NET and all and am trying to put together a simple application which downloads an MP3 file and edits its ID3 tags. This is what I've come up with so far :

Uri link = new System.Uri("URL");
wc.DownloadFileAsync(link, @"C:/music.mp3");
handle.WaitOne();

var file = TagLib.File.Create(@"C:/music.mp3");
file.Tag.Title = "Title";
file.Save();

The top section downloads the file with a pre-defined WebClient, but when I try to open the file in the first line of the second half, I run into this error The process cannot access the file 'C:\music.mp3' because it is being used by another process. which I'm guessing is due to the WebClient.

Any ideas on how to fix this? Thanks.

Sam Axe
  • 33,313
  • 9
  • 55
  • 89
Chirag Galaiya
  • 87
  • 1
  • 1
  • 10
  • Here seems to be the answer for you http://stackoverflow.com/a/28217960/920557 and the idea I guess is to Dispose the client before opening the file again. – Eugene Komisarenko Apr 26 '17 at 19:51
  • If you are writing to Most systems don't give you rights to create files on the root of `C:/` unless your app is an administrator. You may want to try to save it in a subfolder. – Scott Chamberlain Apr 26 '17 at 19:52
  • Yes, @EugeneKomisarenko is right. There is no need for async call in your particular case. Just replace the second line with `wc.DownloadFile(link, @"C:/music.mp3");` and remove the third one. – Dmitry Egorov Apr 26 '17 at 19:55
  • 1
    You want to keep the Async method otherwise the UI will freeze up during download. – Sam Axe Apr 26 '17 at 19:59

1 Answers1

2

If using WebClient.DownloadFileAsync you should subscribe to the DownloadFileCompleted event and perform the remainder of your processing from that event.

Quick and dirty:

WebClient wc = new WebClient();
wc.DownloadfileCompleted += completedHandler;
Uri link = new System.Uri("URL");
wc.DownloadFileAsync(link, @"C:/music.mp3");
//handle.WaitOne();  // dunno what this is doing in here.

function completedHandler(Object sender, AsyncCompletedEventArgs e) {
    var file = TagLib.File.Create(@"C:/music.mp3");
    file.Tag.Title = "Title";
    file.Save();
}
Sam Axe
  • 33,313
  • 9
  • 55
  • 89