c# - 获取 .NET 程序集的日期

标签 c# .net-3.5

<分区>

如何从当前的 .NET 程序集中检索创建日期?

我想添加一些非常简单的功能,使我的应用程序在主程序集构建日期后一周停止工作。我已经编写了在给定日期后终止我的应用程序的代码。我只需要以编程方式从程序集中检索创建日期。

最佳答案

以下内容基于:https://blog.codinghorror.com/determining-build-date-the-hard-way/

public static class ApplicationInformation
{
    /// <summary>
    /// Gets the executing assembly.
    /// </summary>
    /// <value>The executing assembly.</value>
    public static System.Reflection.Assembly ExecutingAssembly
    {
        get { return executingAssembly ?? (executingAssembly = System.Reflection.Assembly.GetExecutingAssembly()); }
    }
    private static System.Reflection.Assembly executingAssembly;

    /// <summary>
    /// Gets the executing assembly version.
    /// </summary>
    /// <value>The executing assembly version.</value>
    public static System.Version ExecutingAssemblyVersion
    {
        get { return executingAssemblyVersion ?? (executingAssemblyVersion = ExecutingAssembly.GetName().Version); }
    }
    private static System.Version executingAssemblyVersion;

    /// <summary>
    /// Gets the compile date of the currently executing assembly.
    /// </summary>
    /// <value>The compile date.</value>
    public static System.DateTime CompileDate
    {
        get
        {
            if (!compileDate.HasValue)
                compileDate = RetrieveLinkerTimestamp(ExecutingAssembly.Location);
            return compileDate ?? new System.DateTime();
        }
    }
    private static System.DateTime? compileDate;

    /// <summary>
    /// Retrieves the linker timestamp.
    /// </summary>
    /// <param name="filePath">The file path.</param>
    /// <returns></returns>
    /// <remarks>http://www.codinghorror.com/blog/2005/04/determining-build-date-the-hard-way.html</remarks>
    private static System.DateTime RetrieveLinkerTimestamp(string filePath)
    {
        const int peHeaderOffset = 60;
        const int linkerTimestampOffset = 8;
        var b = new byte[2048];
        System.IO.FileStream s = null;
        try
        {
            s = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            s.Read(b, 0, 2048);
        }
        finally
        {
            if(s != null)
                s.Close();
        }
        var dt = new System.DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(System.BitConverter.ToInt32(b, System.BitConverter.ToInt32(b, peHeaderOffset) + linkerTimestampOffset));
        return dt.AddHours(System.TimeZone.CurrentTimeZone.GetUtcOffset(dt).Hours);
    }
}

关于c# - 获取 .NET 程序集的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2050396/

相关文章:

c# - 如何为 ref 传递的参数取消引用 ParameterType

c# - 如何在 lambda 表达式 mvc 中使用 select many

.net-3.5 - XBAP 应用程序不会下载 : The operation has timed out?

c# - 使用 File.ReadAllText 的静态字符串

c# - XML LINQ 查询不返回任何数据

c# - 使用 windbg 检测挂起的 C# 应用程序中的死锁

c# - 如何将结构的实例分配给包含该结构的类?

c# - 生成 MySQL 命令字符串

c# - 此代码在做什么-拆分字符串并创建GUID

c# - C++ 17 中的 std::byte 是否等同于 C# 中的字节?