错误:进程无法访问文件' Companion.jpg'因为它正被另一个进程使用

时间:2014-08-16 21:30:21

标签: 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);
        }
    }
    }
}

1 个答案:

答案 0 :(得分:7)

我怀疑这是问题所在:

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

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

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

你应该处理已调整大小的图像,尽管至少它不会保留文件句柄。

请注意,您是否拥有几乎完全相同的代码块,无论是否有两个以上的文件。有条件地选择大小会更清晰:

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。