2013-08-07 23 views
0

我想在global.asax中使用DateTime給文件的名稱,但它會給出錯誤。你能幫忙嗎?DateTime不工作在Global.asax在c#

我用於DateTime的代碼;

public void callFileCreate() 
{ 
    string path = ConfigurationManager.AppSettings["LogFileFolder"].ToString(); 


    string filename = HttpContext.Current.Server.MapPath(path + "\\Log_" + DateTime.Now.ToShortDateString().Replace("/", ".") + "_" + (DateTime.Now.ToLongTimeString()).Replace(":", "_") + ".txt"); 
    TraceFilePath = HttpContext.Current.Server.MapPath(path + "\\Scheduler" + DateTime.Now.ToShortDateString().Replace("/", ".") + "_" + (DateTime.Now.ToLongTimeString()).Replace(":", "_") + ".txt"); 
    FileStream fs = null, fs1 = null; 
    fs = File.Create(filename); 
    fs1 = File.Create(TraceFilePath); 
    ErrorFilePath = filename; 
} 
+4

它給了什麼錯誤? – M4N

+0

你忘了在根目錄中使用路徑,即'ConfigurationManager.AppSettings [「LogFileFolder」]中的'〜/ yourpath'? –

+0

它給出了什麼錯誤? –

回答

1

您應該使用Path類,如果你有工作路徑:如果

string path = ConfigurationManager.AppSettings["LogFileFolder"].ToString(); 
string fileName = string.Format("{0}_{1}_{2}.txt" 
    , "Log" 
    , DateTime.Today.ToString("dd.MM.yyyy") // change according to your actual culture 
    , DateTime.Now.ToString("HH_mm_ss")); 
string fullPath = Path.Combine(path, fileName); 

不知道,幫您解決問題,但它增加了可讀性,反正避免粗心犯錯。

0

你不寫你得到什麼錯誤。但在這裏是如何可以簡化你的代碼的一些提示:

var dir = HttpContext.Current.Server.MapPath(
       ConfigurationManager.AppSettings["LogFileFolder"].ToString()); 
var dt = DateTime.Now.ToString("yyyy.MM.dd_HH.mm.ss"); 

var logFilePath = Path.Combine(dir, string.Format("Log_{0}.txt", dt)); 
var traceFilePath = Path.Combine(dir, string.Format("Scheduler_{0}.txt", dt)); 

var fs = File.Create(logFilePath); 
var fs1 = File.Create(traceFilePath); 

注:

  • ,如果應用程序的設置項LogFileFolder已經包含了(絕對)文件系統的路徑,例如c:\temp,那麼你不應該撥打Server.MapPath()
  • 一旦不再需要流(或將其放入using塊中),您應該致電fs.Close()。否則,另一個創建(相同)文件的嘗試將導致異常。
+0

你不知道OP的文化,所以你不知道它是'yyyy.MM.dd'還是'dd.MM.yyyy'或whatelse。 –

+0

@Tim:我想你希望文件名具有一致的(即與文化無關的)格式,而不依賴於當前的文化(對於web應用程序中的每個請求/用戶可能不同)。 – M4N

+0

是的,但OP的原始代碼依賴於文化,不確定是否需要。 –