【发布时间】:2016-03-31 07:49:01
【问题描述】:
我想为不同的操作制作日志。我每天都以日期为文件名创建一个新文件。现在,如果目录不存在,我希望系统为我创建目录。我搜索了这个主题,所有的答案都是一样的:使用Directory.CreateDirectory(FilePath);。然而,这似乎不起作用。可能遗漏了一些明显的东西。
代码如下:
public class ElderlyHomeLog : ILog
{
private const string FilePath = "/Logs/WZCLogs/";
public void MakeLog(string text)
{
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
string logFile = DateTime.Now.ToString("ddMMyyyy") + ".txt";
if (!File.Exists(HostingEnvironment.ApplicationPhysicalPath + FilePath + logFile))
{
FileStream f = File.Create(HostingEnvironment.ApplicationPhysicalPath + FilePath + logFile);
f.Close();
}
using (StreamWriter sw = new StreamWriter(HostingEnvironment.ApplicationPhysicalPath + FilePath + logFile, true))
{
sw.WriteLine(text);
sw.Close();
}
}
}
错误信息:
发生“System.IO.DirectoryNotFoundException”类型的异常 在 mscorlib.dll 中,但未在用户代码中处理
附加信息:找不到路径的一部分 'C:\Users\***\Source\Repos\Project\ProjectName\Logs\WZCLogs\31032016.txt'。
【问题讨论】:
-
错误信息或描述?
-
你有没有试过给它一个要创建的目录的绝对路径?此外,如果您使用
Path.Combine来组合路径,那么您将不必担心目录分隔符。 -
FilePath 变量可能不完整?
-
你真的需要重新发明方轮吗? nlog-project.org 呢?
-
另外,您是否考虑过将日志文件命名为“yyyyMMdd”,以便按名称排序也按日期排序?
标签: c# logging asp.net-mvc-5