GThree
GThree

Reputation: 3562

The process cannot access the file because it is being used by another process error while moving image

I've a folder named testPhotos with some images. Based on the image creation date, I want to create a new folder by image creation year and then move the image to that folder.

For example, testPhotos has image named 01.jpg which was created on 2011. So I want to create a folder named 2011 inside testPhotos like testPhotos\2011 and move image to that folder. While doing this I am getting The process cannot access the file because it is being used by another process. error while moving image from one folder to another.

Code:

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

Any ideas?

Upvotes: 0

Views: 1259

Answers (1)

Michael Sander
Michael Sander

Reputation: 2722

This looks like a missing dispose on the image, try with the following:

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

Upvotes: 2

Related Questions