1
我做了一個函數,它可以循環並刪除給定目錄中的兩個相似圖像。 (甚至多個目錄):IOException文件被另一個進程使用
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 < 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 < distinctsha1codes.Count; i++)
if (distinctsha1codes.Contains(Gifs[i].Sha1Code))
{
for (int j = 0; j < distinctsha1codes.Count; j++)
if (distinctsha1codes[j] != null && distinctsha1codes[j].ToString() == Gifs[i].Sha1Code)
{
distinctsha1codes[j] = Gifs[i] = null;
break;
}
}
try
{
for (int i = 0; i < Gifs.Length; i++)
if (Gifs[i] != null)
File.Delete(Gifs[i].Location);
}
catch (IOException)
{
}
}
的問題是,我留下了我要刪除的文件列表後,我不能刪除它們,因爲我碰到一個「System.IO.IOException文件正在被另一個進程使用......「
我試着用procexp來查看哪些進程正在使用我的文件,而且似乎MyApplication.vshost.exe正在使用這些文件。它開始使用該行上的文件:
sha1.ComputeHash(GifImages.ImageToByteArray(Image.FromFile(images [i])));
含義Image.FromFile(images [i])打開文件,但從不關閉它。
我會在下次閱讀文檔。到了我知道有問題的功能是什麼的地方,但忘了這麼做...順便說一句,我只能在5分鐘內接受你的答案。 – 2011-05-29 22:16:26
@或Betzalel:哈哈,我們都這樣做。我昨天上午3點左右做了同樣的事情。 – 2011-05-29 22:17:03