我有一个名为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);
}
有什么想法吗?
答案 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);
}
}