我想渲染(用于内部调试/信息)程序集的最后修改日期,因此我将知道何时部署某个网站。

是否可以通过反思获得它?

我得到这样的版本:

Assembly.GetExecutingAssembly().GetName().Version.ToString();

我正在寻找类似的东西 - 我不想打开物理文件,获取其属性或类似的东西,因为我将在母版页中呈现它,并且不希望这样有点开销。

有帮助吗?

解决方案

我将第二个pYrania的回答:

System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.FileInfo fileInfo = new System.IO.FileInfo(assembly.Location);
DateTime lastModified = fileInfo.LastWriteTime;

但是加上这个:

您提到您不想访问文件系统,因为它位于您的母版页中,并且您不希望为每个页面命中额外的文件系统。所以不要,只需在Application load事件中访问一次,然后将其存储为应用程序级变量。

其他提示

如果您在AssemblyInfo中默认修订版和内部版本号:

[assembly: AssemblyVersion("1.0.*")]

您可以通过以下方式获取大致的构建日期:

Version version = typeof(MyType).Assembly.GetName().Version;
DateTime date = new DateTime(2000, 1, 1)
    .AddDays(version.Build)
    .AddSeconds(version.Revision * 2);

这个怎么样?

System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.FileInfo fileInfo = new System.IO.FileInfo(assembly.Location);
DateTime lastModified = fileInfo.LastWriteTime;

有些人认为大会没有建立日期,但你知道他们错了什么, 您可以从嵌入在可执行文件中的 PE头中检索链接器时间戳,如下所示工作(我自己没有测试过代码)

private DateTime RetrieveLinkerTimestamp()
{
    string filePath = System.Reflection.Assembly.GetCallingAssembly().Location;
    const int c_PeHeaderOffset = 60;
    const int c_LinkerTimestampOffset = 8;
    byte[] b = new byte[2048];
    System.IO.Stream 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();
        }
    }

    int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset);
    int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset);
    DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0);
    dt = dt.AddSeconds(secondsSince1970);
    dt = dt.AddHours(TimeZone.CurrentTimeZone.GetUtcOffset(dt).Hours);
    return dt;
}

或者如果汇编是你自己更好的,你可以使用以下方法简单易行

在下面添加到预构建事件命令行:

echo %date% %time% > "$(ProjectDir)\Resources\BuildDate.txt"

将此文件添加为资源,现在您的资源中包含“BuildDate”字符串。

我已从此问题中获取了两个答案

2038 后, RetrieveLinkerTimestamp 解决方案无法使用 1970 中的 int32 。我建议使用以下内容(虽然这可能也有其局限性):

IO.File.GetLastWriteTime(Reflection.Assembly.GetExecutingAssembly().Location)

我不相信程序集包含最后修改的信息,因为这是操作系统属性。我相信获取此信息的唯一方法是通过文件句柄。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top