【问题标题】:IOException File Is Used By Another ProcessIOException 文件被另一个进程使用
【发布时间】:2011-09-04 11:18:56
【问题描述】:

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

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 file is being used by another process...”

我尝试使用 procexp 查看哪些进程正在使用我的文件,并且似乎 MyApplication.vshost.exe 正在使用这些文件。它开始使用该行上的文件:

sha1.ComputeHash(GifImages.ImageToByteArray(Image.FromFile(images[i])));

意思是 Image.FromFile(images[i]) 打开文件但从不关闭它。

【问题讨论】:

    标签: c# image process ioexception


    【解决方案1】:

    documentation 告诉你很多:

    文件保持锁定状态,直到图像被释放。

    因此,您需要在尝试删除该图像之前对其进行处理。只需将其保留尽可能短的时间,如下所示:

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

    【讨论】:

    • 下次我会阅读文档。到了我知道有问题的功能是什么的部分,但忘了这样做......顺便说一句,我只能在 5 分钟内接受你的答案。
    • @Or Betzalel:哈哈,我们都这样做。我昨晚凌晨 3 点左右做了同样的事情。
    猜你喜欢
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 2020-03-11
    • 1970-01-01
    • 2021-02-27
    • 2022-11-18
    相关资源
    最近更新 更多