Files
Common-VS2019/SacsStandardBase/Base/Utils/AssemblyUtil.cs
T
2025-11-20 17:17:40 +00:00

63 lines
2.0 KiB
C#

using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Sarand.Net.Standard.Base.Utils
{
//=======================================================================
public static class AssemblyUtil
{
//-------------------------------------------------------------------
#region Gets the build date and time (by reading the COFF header)
// http://msdn.microsoft.com/en-us/library/ms680313
struct _IMAGE_FILE_HEADER
{
#pragma warning disable CS0649
public ushort Machine;
public ushort NumberOfSections;
public uint TimeDateStamp;
public uint PointerToSymbolTable;
public uint NumberOfSymbols;
public ushort SizeOfOptionalHeader;
public ushort Characteristics;
#pragma warning restore CS0649
};
public static DateTime GetBuildDateTime(this Assembly assembly)
{
var path = assembly.Location;
if (File.Exists(path))
{
var buffer = new byte[Math.Max(Marshal.SizeOf(typeof(_IMAGE_FILE_HEADER)), 4)];
using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
fileStream.Position = 0x3C;
fileStream.Read(buffer, 0, 4);
fileStream.Position = BitConverter.ToUInt32(buffer, 0); // COFF header offset
fileStream.Read(buffer, 0, 4); // "PE\0\0"
fileStream.Read(buffer, 0, buffer.Length);
}
var pinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
try
{
var coffHeader = (_IMAGE_FILE_HEADER)Marshal.PtrToStructure(pinnedBuffer.AddrOfPinnedObject(), typeof(_IMAGE_FILE_HEADER));
DateTime buildDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return buildDate.AddSeconds(coffHeader.TimeDateStamp);
//return TimeZoneInfo.Local.ToLocalTime(new DateTime(1970, 1, 1) + new TimeSpan(coffHeader.TimeDateStamp * TimeSpan.TicksPerSecond));
}
finally
{
pinnedBuffer.Free();
}
}
return new DateTime();
}
#endregion
//-------------------------------------------------------------------
}
//=======================================================================
}