Created
September 16, 2014 22:07
-
-
Save AdamMaras/5e036e5993806540c30d to your computer and use it in GitHub Desktop.
Get assembly linker timestamp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Concurrent; | |
using System.IO; | |
using System.Reflection; | |
public static class AssemblyExtensions | |
{ | |
private const int PortableExecutableHeaderLocationOffset = 60; | |
private const int LinkerTimestampLocationOffset = 8; | |
private static readonly ConcurrentDictionary<Assembly, DateTime?> LinkerTimestampCache = | |
new ConcurrentDictionary<Assembly, DateTime?>(); | |
public static DateTime? GetAssemblyLinkerTimestamp(this Assembly assembly) | |
{ | |
return LinkerTimestampCache.GetOrAdd(assembly, GetAssemblyLinkerTimestampInternal); | |
} | |
private static DateTime? GetAssemblyLinkerTimestampInternal(Assembly assembly) | |
{ | |
string filePath; | |
try | |
{ | |
filePath = assembly.Location; | |
} | |
catch { return null;} | |
if (string.IsNullOrWhiteSpace(filePath)) { return null; } | |
var buffer = new byte[2048]; | |
int bytesRead; | |
try | |
{ | |
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) | |
{ | |
bytesRead = fileStream.Read(buffer, 0, buffer.Length); | |
} | |
} | |
catch { return null; } | |
if (bytesRead < PortableExecutableHeaderLocationOffset + 4) { return null; } | |
var portableExecutableHeaderLocation = BitConverter.ToInt32(buffer, PortableExecutableHeaderLocationOffset); | |
var linkerTimestampLocation = portableExecutableHeaderLocation + LinkerTimestampLocationOffset; | |
if (bytesRead < linkerTimestampLocation + 4) { return null; } | |
var linkerTimestamp = BitConverter.ToInt32(buffer, linkerTimestampLocation); | |
var convertedLinkerTimestamp = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(linkerTimestamp); | |
var localLinkerTimestamp = convertedLinkerTimestamp.ToLocalTime(); | |
return localLinkerTimestamp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment