该进程无法访问该文件,因为它在移动图像时被另一个进程错误使用

时间:2015-08-12 21:15:40

标签: c#

我有一个名为testPhotos的文件夹,里面有一些图片。根据图像创建日期,我想按图像创建年份创建一个新文件夹,然后将图像移动到该文件夹​​。

例如,testPhotos的图片名为01.jpg,是在2011年创建的。所以我想在2011内创建一个名为testPhotos的文件夹,如testPhotos\2011并将图像移动到该文件夹​​。在这样做时,我得到了The process cannot access the file because it is being used by another process. error while moving image from one folder to another.

代码:

private void button1_Click(object sender, EventArgs e)
{
    var creationDate = new DateTime();
    var dateList = new List<String>();
    var fileName = String.Empty;
    var sourceFolder = @"C:\My Stuff\Test Porjects\testPhotos";

    String[] images = Directory.GetFiles(sourceFolder);

    if (images.Count() > 0)
    {
        foreach (var imagePath in images)
        {
            fileName = Path.GetFileName(imagePath);
            creationDate = GetDateTakenFromImage(imagePath);
            var date = creationDate.GetDateTimeFormats()[5].Replace("-", "/");

            if (!String.IsNullOrEmpty(date))
            {
                var year = date.Substring(0, 4);
                var destinationFolder = sourceFolder + "\\" + year;

                if (!Directory.Exists(destinationFolder))
                {
                    Directory.CreateDirectory(destinationFolder);

                    String fileToMove = sourceFolder+ "\\" + fileName;
                    String moveTo = destinationFolder + "\\" + fileName;

                    File.Move(fileToMove, moveTo);

                }
            }
        }
    }
}

private DateTime GetDateTakenFromImage(string path)
{
    Image myImage = Image.FromFile(path);
    PropertyItem propItem = myImage.GetPropertyItem(36867);
    string dateTaken = new Regex(":").Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);
    return DateTime.Parse(dateTaken);
}

Screenshot of error

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

这看起来像图像上缺少处置,请尝试以下操作:

private DateTime GetDateTakenFromImage(string path)
{
    using (Image myImage = Image.FromFile(path))
    {
        PropertyItem propItem = myImage.GetPropertyItem(36867);
        string dateTaken = new Regex(":").Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);
        return DateTime.Parse(dateTaken);
    }
}