我想记录不同的操作日志。我每天都用日期作为文件名创建一个新的文件。现在,如果目录不存在,我希望系统为我创建目录。我已经搜索了这个主题,所有答案都指向同一件事:使用 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”类型的异常, 但在用户代码中没有处理。
其他信息:无法找到路径的一部分 'C:\Users\***\Source\Repos\Project\ProjectName\Logs\WZCLogs\31032016.txt'。
Path.Combine
来组合路径,那么你就不必担心目录分隔符字符了。 - Andrew Morton