c# - 错误 : The process cannot access the file 'Companion.jpg' because it is being used by another process

标签 c# error-handling

我在尝试从目录中删除文件时遇到问题,因为它说另一个进程正在使用一个文件。运行 cmdCombine 方法后,我不知道如何删除文件夹中的所有文件。这是代码,请提供一点帮助:

    private void cmdCombine_Click(object sender, EventArgs e)
    {
        DirectoryInfo directory = new DirectoryInfo(@"C:\Users\Elder Zollinger\Desktop\Images");
        if (directory != null)
        {
            FileInfo[] files = directory.GetFiles();
            ResizeImages(files);

        }
        DirectoryInfo directory2 = new DirectoryInfo(@"C:\Users\Elder Zollinger\Desktop\Upload");
        if (directory2 != null)
        {
            FileInfo[] files = directory2.GetFiles();
            CombineImages(files);
            System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(@"C:\Users\Elder Zollinger\Desktop\Images");

            foreach (FileInfo file2 in downloadedMessageInfo.GetFiles())
            {
                file2.Delete();
            }
            foreach (DirectoryInfo dir in downloadedMessageInfo.GetDirectories())
            {
                dir.Delete(true);
            }
        }

    }
    //Method for resizing the images
    private void ResizeImages(FileInfo[] files)
    {
        //Set Count integers and strings to save files
        int fileCount = Directory.GetFiles(@"C:\Users\Elder Zollinger\Desktop\Images").Length;
        int count = 1;
        string fileNameOnly = Path.GetFileNameWithoutExtension(@"C:\Users\Elder Zollinger\Desktop\Upload\NewImage.jpg");
        string extension = Path.GetExtension(@"C:\Users\Elder Zollinger\Desktop\Upload\NewImage.jpg");
        string uploadPath = Path.GetDirectoryName(@"C:\Users\Elder Zollinger\Desktop\Upload\NewImage.jpg");
        string newFullUploadPath = @"C:\Users\Elder Zollinger\Desktop\Upload\NewImage.jpg";

        //Read Files in the folder
        foreach (FileInfo file in files)
        {
            //Create a new file name that doesnt exist
            while (File.Exists(newFullUploadPath))
            {
                string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
                newFullUploadPath = Path.Combine(uploadPath, tempFileName + extension);
            }

            //Resize and save images when there is more than 2
            if (fileCount > 2)
            {
                Image img = Image.FromFile(file.FullName);
                var newImage = resizeImage(img, new Size(66, 200));
                newImage.Save(newFullUploadPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }

            //Resize and save images for 1 or 2 images
            else
            {
                Image img = Image.FromFile(file.FullName);
                var newImage = resizeImage(img, new Size(100, 200));
                newImage.Save(newFullUploadPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
    }

    //Stitch Images
    private void CombineImages(FileInfo[] files)
    {
        //Create strings for saved images
        int count = 1;
        string fileNameOnly = Path.GetFileNameWithoutExtension(@"C:\Users\Elder Zollinger\Desktop\Dump\Final.jpg");
        string extension = Path.GetExtension(@"C:\Users\Elder Zollinger\Desktop\Dump\Final.jpg");
        string uploadPath = Path.GetDirectoryName(@"C:\Users\Elder Zollinger\Desktop\Dump\Final.jpg");
        string newFullUploadPath = @"C:\Users\Elder Zollinger\Desktop\Dump\Final.jpg";
        List<int> imageHeights = new List<int>();
        int nIndex = 0;
        int width = 0;
        foreach (FileInfo file in files)
        {
            Image img = Image.FromFile(file.FullName);
            imageHeights.Add(img.Height);
            width += img.Width;
            img.Dispose();
        }
        imageHeights.Sort();
        int height = imageHeights[imageHeights.Count - 1];
        Bitmap img3 = new Bitmap(width, height);
        Graphics g = Graphics.FromImage(img3);
        g.Clear(SystemColors.AppWorkspace);
        foreach (FileInfo file in files)
        {
            Image img = Image.FromFile(file.FullName);
            if (nIndex == 0)
            {
                g.DrawImage(img, new Point(0, 0));
                nIndex++;
                width = img.Width;
            }
            else
            {
                g.DrawImage(img, new Point(width, 0));
                width += img.Width;
            }
            img.Dispose();
        }
        g.Dispose();

        while (File.Exists(newFullUploadPath))
        {
            string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
            newFullUploadPath = Path.Combine(uploadPath, tempFileName + extension);
        }
        img3.Save(newFullUploadPath, System.Drawing.Imaging.ImageFormat.Jpeg);
        img3.Dispose();
        imageLocation.Image = Image.FromFile(newFullUploadPath);
        foreach (FileInfo file in files)
        {
            file.Delete();
        }
    }

    //Method to resize the images
    private static Image resizeImage(Image imgToResize, Size size)
    {
        return (Image)(new Bitmap(imgToResize, size));
    }

    private void SelectImages_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        openFileDialog1.InitialDirectory = "c:\\";
        openFileDialog1.Filter = "png files (*.png)|*.png|All files (*.*)|*.*";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.RestoreDirectory = true;

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
                if ((myStream = openFileDialog1.OpenFile()) != null)
                {
                    int count = 1;
                    string fileNameOnly = Path.GetFileNameWithoutExtension(@"C:\Users\Elder Zollinger\Desktop\Images\Companion.jpg");
                    string extension = Path.GetExtension(@"C:\Users\Elder Zollinger\Desktop\Images\Companion.jpg");
                    string uploadPath = Path.GetDirectoryName(@"C:\Users\Elder Zollinger\Desktop\Images\Companion.jpg");
                    string newFullUploadPath = @"C:\Users\Elder Zollinger\Desktop\Images\Companion.jpg";
                    while (File.Exists(newFullUploadPath))
            {
                string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
                newFullUploadPath = Path.Combine(uploadPath, tempFileName + extension);
            }
                    System.IO.File.Copy(openFileDialog1.FileName, newFullUploadPath);
                }
            }
        }

    private void Clear_Click(object sender, EventArgs e)
    {
        imageLocation.Image = null;
        System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(@"C:\Users\Elder Zollinger\Desktop\Images");

        foreach (FileInfo file in downloadedMessageInfo.GetFiles())
        {
            file.Delete();
        }
        foreach (DirectoryInfo dir in downloadedMessageInfo.GetDirectories())
        {
            dir.Delete(true);
        }
    }
    }
}

最佳答案

我怀疑这是问题所在:

Image img = Image.FromFile(file.FullName);

打开 文件 - 但您永远不会处理同一个对象,因此文件将一直打开,直到对象完成。 Image 实现了 IDisposable,因此您应该使用 using 语句:

using (Image image = ...)
{
    ...
}

您还应该 处理调整大小的图像,尽管至少它不会占用文件句柄。

请注意,无论文件是否超过两个,您都得到了几乎完全相同的代码块。有条件地选择 just the size 会更干净:

Size size = fileCount > 2 ? new Size(66, 200) : new Size(100, 200);
using (Image original = Image.FromFile(file.FullName))
using (Image resized = ResizeImage(original, size))
{
     resized.Save(newFullUploadPath, ImageFormat.Jpeg);
}

更清洁,IMO。

关于c# - 错误 : The process cannot access the file 'Companion.jpg' because it is being used by another process,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25344176/

相关文章:

c# - 使用 Graph 创建团队后是否需要等待

c# - EntityFramework 的验证框架

c# - PDFsharp 在 Azure 中生成空白页面,但在本地工作

python - 你如何在 Python 中测试 file.read() 错误?

batch-file - 使用ERRORLEVEL检索InstallUtil的退出状态

c# - 在 C# 中重新启动 foreach 循环?

c# - 如何在 C# Winforms 应用程序上使用模拟以管理员权限运行?

javascript - Uncaught SyntaxError : Unexpected token '.' - how do I catch it?

java - 错误代码或异常 : How to communicate errors from model to controller in my case?

iPhone - 将字典写入文件 : handling errors