title: The process cannot access the file because it is being used by another process
body: <p>I am running a program where a file gets uploaded to a folder in IIS,and then is processed to extract some values from it. I use a WCF service to perform the process, and BackgroundUploader to upload the file to IIS. However, after the upload process is complete, I get the error "The process cannot access the file x because it is being used by another process." Based on similar questions asked here, I gathered that the file concerned needs to be in a using statement. I tried to modify my code to the following, but it didn't work, and I am not sure if it is even right.</p>
  
  <pre><code>namespace App17
  {
  public sealed partial class MainPage : Page, IDisposable
  {
     private CancellationTokenSource cts;      
  
      public void Dispose()
      {
          if (cts != null)
          {
              cts.Dispose();
              cts = null;
          }
  
          GC.SuppressFinalize(this);
      }
  
      public MainPage()
      {
          this.InitializeComponent();
          cts = new CancellationTokenSource();
      }
  
      public async void Button_Click(object sender, RoutedEventArgs e)
      {
          try
          {               
              Uri uri = new Uri(serverAddressField.Text.Trim());
              FileOpenPicker picker = new FileOpenPicker();
              picker.FileTypeFilter.Add("*");
              StorageFile file = await picker.PickSingleFileAsync();
  
  
              using (var stream = await file.OpenAsync(FileAccessMode.Read))
              {
                  GlobalClass.filecontent = file.Name;
                  GlobalClass.filepath = file.Path;
                  BackgroundUploader uploader = new BackgroundUploader();
                  uploader.SetRequestHeader("Filename", file.Name);
                  UploadOperation upload = uploader.CreateUpload(uri, file);
                  await HandleUploadAsync(upload, true);
                  stream.Dispose();
              }
  
  
          }
  
          catch (Exception ex)
          {
              string message = ex.ToString();
              var dialog = new MessageDialog(message);
              await dialog.ShowAsync();
              Log(message);
          }
  
      }
  
  
     private void CancelAll(object sender, RoutedEventArgs e)
     {
         Log("Canceling all active uploads");
         cts.Cancel();
         cts.Dispose();
         cts = new CancellationTokenSource();
     }
  
  
     private async Task HandleUploadAsync(UploadOperation upload, bool start)
     {
         try
         {
             Progress&lt;UploadOperation&gt; progressCallback = new Progress&lt;UploadOperation&gt;(UploadProgress);
             if (start)
             {
  
                 await upload.StartAsync().AsTask(cts.Token, progressCallback);
             }
             else
             {
                 // The upload was already running when the application started, re-attach the progress handler.
                 await upload.AttachAsync().AsTask(cts.Token, progressCallback);
             }
  
             ResponseInformation response = upload.GetResponseInformation();
             Log(String.Format("Completed: {0}, Status Code: {1}", upload.Guid, response.StatusCode));
  
             cts.Dispose();
         }
  
         catch (TaskCanceledException)
         {
             Log("Upload cancelled.");
         }
         catch (Exception ex)
         {
             string message = ex.ToString();
             var dialog = new MessageDialog(message);
             await dialog.ShowAsync();
             Log(message);
         }
     }
  
  
  
     private void Log(string message)
     {
         outputField.Text += message + "\r\n";
     }
  
  
     private async void LogStatus(string message)
     {
         var dialog = new MessageDialog(message);
         await dialog.ShowAsync();
         Log(message);
     }
  
  
     private void UploadProgress(UploadOperation upload)
     {
         BackgroundUploadProgress currentProgress = upload.Progress;
         MarshalLog(String.Format(CultureInfo.CurrentCulture, "Progress: {0}, Status: {1}", upload.Guid,
             currentProgress.Status));
         double percentSent = 100;
         if (currentProgress.TotalBytesToSend &gt; 0)
         {
             percentSent = currentProgress.BytesSent * 100 / currentProgress.TotalBytesToSend;
         }
  
         MarshalLog(String.Format(CultureInfo.CurrentCulture,
             " - Sent bytes: {0} of {1} ({2}%), Received bytes: {3} of {4}", currentProgress.BytesSent,
             currentProgress.TotalBytesToSend, percentSent, currentProgress.BytesReceived, currentProgress.TotalBytesToReceive));
  
         if (currentProgress.HasRestarted)
         {
             MarshalLog(" - Upload restarted");
         }
  
         if (currentProgress.HasResponseChanged)
         {
  
             MarshalLog(" - Response updated; Header count: " + upload.GetResponseInformation().Headers.Count);
  
  
         }
     }
  
  
     private void MarshalLog(string value)
     {
         var ignore = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =&gt;
         {
             Log(value);
         });
     }
  
  
  }
  </code></pre>
  
  <p>}</p>
  
  <p>After this is done, the file name is sent to a WCF service which will access and process the uploaded file to extract certain values. It is at this point I receive the error. I would truly appreciate some help.</p>
  
  <pre><code>public async void Extract_Button_Click(object sender, RoutedEventArgs e)
      {
        ServiceReference1.Service1Client MyService = new ServiceReference1.Service1Client();
        string filename = GlobalClass.filecontent;            
        string filepath = @"C:\Users\R\Documents\Visual Studio 2015\Projects\WCF\WCF\Uploads\"+ filename;
        bool x = await MyService.ReadECGAsync(filename, filepath);
  
      }
  </code></pre>
  
  <p>EDIT: Code before I added the using block</p>
  
  <pre><code>     try
          {
              Uri uri = new Uri(serverAddressField.Text.Trim());
              FileOpenPicker picker = new FileOpenPicker();
              picker.FileTypeFilter.Add("*");
              StorageFile file = await picker.PickSingleFileAsync();
              GlobalClass.filecontent = file.Name;
              GlobalClass.filepath = file.Path;
              BackgroundUploader uploader = new BackgroundUploader();
              uploader.SetRequestHeader("Filename", file.Name);
              UploadOperation upload = uploader.CreateUpload(uri, file);
              await HandleUploadAsync(upload, true);
          }
  </code></pre>