Skip to content

Instantly share code, notes, and snippets.

@AliFlux
Last active January 27, 2024 08:56
Show Gist options
  • Save AliFlux/fd166223a76668d2861eaf861023bff6 to your computer and use it in GitHub Desktop.
Save AliFlux/fd166223a76668d2861eaf861023bff6 to your computer and use it in GitHub Desktop.
Process exiftool tags using C#
public static Dictionary<string, string> getExifDataViaTool(string sourceFile, string parameters = "-a")
{
var result = new Dictionary<string, string>();
// escaping path command line
sourceFile = Regex.Replace(sourceFile, @"(\\*)" + "\"", @"$1\$0");
sourceFile = Regex.Replace(sourceFile, @"^(.*\s.*?)(\\*)$", "\"$1$2$2\"");
var argumentsString = parameters + " " + sourceFile;
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = @"exiftool.exe";
startInfo.Arguments = argumentsString;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
process.StartInfo = startInfo;
process.Start();
process.WaitForExit(5000);
string output = process.StandardOutput.ReadToEnd();
string err = process.StandardError.ReadToEnd();
if (err.ToLower().Contains("error"))
{
throw new MetadataException("Exiftool threw an exception: " + output + "\n" + err);
}
string[] lines = output.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
foreach(var line in lines)
{
var pair = line.Split(new char[] { ':' }, 2);
if(pair.Length >= 2)
{
var key = pair[0].TrimEnd();
var value = pair[1].TrimStart();
result[key] = value;
}
}
return result;
}
@AliFlux
Copy link
Author

AliFlux commented Mar 2, 2017

Here's how to use it:

var data = getExifDataViaTool(@"E:\path\to\file.png"); // returns a dictionary<string, string>
var fileSize = data["File Size"];
var fileType = data["File Type"];

Cheers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment