using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Xml;
namespace GetDateImageTaken
{
class GetDateTaken
{
///
/// Gets the date a picture was taken.
///
/// Full path to the image file, including path and file name.
static void Main(string[] args)
{
try
{
if (args.Length == 1)
{
FileInfo imgFile = new FileInfo(args[0]);
if (imgFile.Exists)
{
DateTime dateTaken = GetEXIFDateTaken(imgFile.FullName);
Console.WriteLine("The picture was taken: {0}", dateTaken.ToString());
}
else
{
Console.WriteLine("File does not exist!");
}
}
else if (args.Length > 1)
{
Console.WriteLine("Too many arguments passed!");
}
else
{
Console.WriteLine("File path missing!");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
///
/// Gets the date a picture was taken from the EXIF metadata and returns it in a DateTime object.
///
/// Full path to the image file, including directory and file name.
/// DateTime object
public static DateTime GetEXIFDateTaken(string filePathAndName)
{
// Load the image
Bitmap img = new Bitmap(filePathAndName);
// Convert the HEX ID value (remove the "0x" prefix) to an integer
int id = int.Parse("9003", System.Globalization.NumberStyles.AllowHexSpecifier); //36867
// Get the 'Date Created' Property Item
PropertyItem prop = img.GetPropertyItem(id);
byte[] asciiBytes = prop.Value;
// Convert the EXIF byte array to a string
string strDate = System.Text.Encoding.ASCII.GetString(asciiBytes);
// Convert the string to a DateTime object
DateTime dateTaken = ConvertEXIFStringToDate(strDate);
return dateTaken;
}
///
/// Massages the uniquely formatted EXIF DateCreated string and converts it to a DateTime object.
///
/// format is "YYYY:MM:DD HH:MM:SS"
/// DateTime object
private static DateTime ConvertEXIFStringToDate(string date)
{
DateTime dateCreated = new DateTime();
// Pull out the year, month, day and time individually from the string
string dateYear = date.Substring(0, 4);
string dateMonth = date.Substring(5, 2);
string dateDay = date.Substring(8, 2);
string dateHourMinSec = date.Substring(11, 8);
// Create a stringbuilder that is formatted for conversion to DateTime
StringBuilder sbDateCreated = new StringBuilder();
sbDateCreated.Append(dateMonth + "/");
sbDateCreated.Append(dateDay + "/");
sbDateCreated.Append(dateYear + " ");
sbDateCreated.Append(dateHourMinSec);
// Convert the string to DateTime
dateCreated = Convert.ToDateTime(sbDateCreated.ToString());
return dateCreated;
}
}
}