2010-02-10 44 views
7

我需要編譯日期以某種方式硬編碼到代碼中。將編譯日期添加到代碼中

我該怎麼做?

謝謝

+0

見http://stackoverflow.com/questions/320887/c-put-date-into-program-when-compiled/1835441 – 2010-02-10 07:08:19

回答

5

在我的大部分項目中,我使用了一個函數'RetrieveLinkerTimestamp'。

 public DateTime RetrieveLinkerTimestamp(string filePath) 
    { 
     const int PeHeaderOffset = 60; 
     const int LinkerTimestampOffset = 8; 

     byte[] b = new byte[2048]; 
     Stream s = Stream.Null; 
     try 
     { 
      s = new FileStream(filePath, FileMode.Open, FileAccess.Read); 
      s.Read(b, 0, 2048); 
     } 
     finally 
     { 
      if ((s != null)) s.Close(); 
     } 

     int i = BitConverter.ToInt32(b, PeHeaderOffset); 

     int SecondsSince1970 = BitConverter.ToInt32(b, i + 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; 
    } 

也許這有幫助嗎?

歡呼聲,

基督教

+0

我用System.Reflection.Assembly.GetExecutingAssembly()調用它。位置 它的工作完美 – 2010-02-10 13:23:55

0

源代碼管理或持續集成構建服務器?不是完全編譯時間和代碼,但它會得到一個提交時間和內部版本號。

+0

你的意思是從代碼讀取我的結帳日期?聽起來有點奇怪的解決方案。 – 2010-02-10 07:09:13

2

你可以use a T4 template生成你的代碼,無論你需要這樣的元信息。

<#@ assembly name="System.Core.dll" #> 
<#@ template language="C#v3.5" debug="True" hostspecific="True" #> 
<#@ output extension=".cs" #> 
using System; 

namespace MyNamespace 
{ 
    public class MyClass 
    { 
     // <#= DateTime.Now.ToString() #> 
    } 
} 

該模板將輸出一個類文件看起來像:

using System; 

namespace MyNamespace 
{ 
    public class MyClass 
    { 
     // 2/9/2010 11:06:59 PM 
    } 
} 

你可能need to add a build task or a pre-build step上運行構造每個T4編譯器。