title: IOException File Is Used By Another Process
body: <p>I've made a function that cycles and deletes two similar images in a given directory. (or even multiple directories) : </p>
  
  <pre><code>public void DeleteDoubles()
      {
          SHA512CryptoServiceProvider sha1 = new SHA512CryptoServiceProvider();
          string[] images = Directory.GetFiles(@"C:\" + "Gifs");
          string[] sha1codes = new string[images.Length];
          GifImages[] Gifs = new GifImages[images.Length];
  
          for (int i = 0; i &lt; images.Length; i++)
          {
              sha1.ComputeHash(GifImages.ImageToByteArray(Image.FromFile(images[i])));
              sha1codes[i] = Convert.ToBase64String(sha1.Hash);
              Gifs[i] = new GifImages(images[i], sha1codes[i]);
          }
  
          ArrayList distinctsha1codes = new ArrayList();
          foreach (string sha1code in sha1codes)
              if (!distinctsha1codes.Contains(sha1code))
                  distinctsha1codes.Add(sha1code);
  
          for (int i = 0; i &lt; distinctsha1codes.Count; i++)
              if (distinctsha1codes.Contains(Gifs[i].Sha1Code))
              {
                  for (int j = 0; j &lt; distinctsha1codes.Count; j++)
                      if (distinctsha1codes[j] != null &amp;&amp; distinctsha1codes[j].ToString() == Gifs[i].Sha1Code)
                      {
                          distinctsha1codes[j] = Gifs[i] = null;
                          break;
                      }
              }
  
          try
          {
              for (int i = 0; i &lt; Gifs.Length; i++)
                  if (Gifs[i] != null)
                      File.Delete(Gifs[i].Location);
          }
          catch (IOException)
          {
          }
      }
  </code></pre>
  
  <p>The problem is that after I'm left with the list of files I want to delete, I can't delete them because I get "System.IO.IOException file is being used by another process..."</p>
  
  <p>I tried using procexp to see which processes are using my files and it seems the files are being used by MyApplication.vshost.exe. It starts using the file on that line : </p>
  
  <blockquote>
    <p>sha1.ComputeHash(GifImages.ImageToByteArray(Image.FromFile(images[i])));</p>
  </blockquote>
  
  <p>Meaning Image.FromFile(images[i]) opens the file but never closes it.</p>