title: Wait until file is downloaded from URL via webClient
body: <p>I have struggle with downloading few MB excel file from URL and then work with it. Im using VS2010 so i cant use await keyword.
  My code follows:</p>
  
  <pre><code>using (WebClient webClient = new WebClient())
                  {
                      // setting Windows Authentication
                      webClient.UseDefaultCredentials = true;
                      // event fired ExcelToCsv after file is downloaded
                      webClient.DownloadFileCompleted += (sender, e) =&gt; ExcelToCsv(fileName);
                      // start download
                      webClient.DownloadFileAsync(new Uri("http://serverx/something/Export.ashx"), exportPath);
                  }
  </code></pre>
  
  <p>The line in <code>ExcelToCsv()</code> method</p>
  
  <pre><code>using (FileStream stream = new FileStream(filePath, FileMode.Open))
  </code></pre>
  
  <p>Throws me an error:</p>
  
  <blockquote>
    <p>System.IO.IOException: The process cannot access the file because it
    is being used by another process.</p>
  </blockquote>
  
  <p>I tried <code>webClient.DownloadFile()</code> only without an event but it throws same error. Same error is throwed if i do not dispose too. What can i do ?</p>
  
  <p>Temporary workaround may be <code>Sleep()</code> method but its not bullet proof.</p>
  
  <p>Thank you</p>
  
  <p>EDIT:
  I tried second approach with standard handling but i have mistake in the code</p>
  
  <pre><code>  using (WebClient webClient = new WebClient())
                  {
                      // nastaveni ze webClient ma pouzit Windows Authentication
                      webClient.UseDefaultCredentials = true;
                      // &lt;--- 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);
          }
  </code></pre>
  
  <p>EDIT: approach 3
  I tried this code</p>
  
  <pre><code>while (true)
                  {
                      if (isFileLocked(downloadedFile))
                      {
                          System.Threading.Thread.Sleep(5000); //wait 5s
                          ExcelToCsv(fileName);
                          break;
                      }
                  }
  </code></pre>
  
  <p>and it seems that it is never accessible :/ I dont get it.</p>