我正在尝试在global.asax中使用DateTime来为文件命名,但它会出错。你能帮忙吗?
我用于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;
}
答案 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);
不确定这是否能解决您的问题,但无论如何都会增加可读性并避免不小心的错误。
答案 1 :(得分: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);
注意:
c:\temp
,则不应拨打Server.MapPath()
。fs.Close()
块中),您应该致电using
。否则,另一次创建(相同)文件的尝试将导致异常。