IOException文件被另一个进程使用

本文关键字:进程 另一个 文件 IOException | 更新日期: 2023-09-27 17:57:52

我制作了一个函数,可以循环并删除给定目录中的两个类似图像。(甚至多个目录):

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]));

意思是图像。FromFile(images[i])打开文件,但从不关闭。

IOException文件被另一个进程使用

文档告诉您的同样多:

在释放图像之前,文件一直处于锁定状态。

因此,在尝试删除图像之前,您需要先处理掉它。只需将其保留最短的时间即可,如下所示:

for (int i = 0; i < images.Length; i++)
{
    using( var img = Image.FromFile( images[i] ) )
    {
        sha1.ComputeHash(imageToByteArray(img));
    }
    sha1codes[i] = Convert.ToBase64String(sha1.Hash);
    Gifs[i] = new GifImages(images[i], sha1codes[i]);
}