cki*_*ndt 13 c# logging asp.net-mvc-5
我想为不同的操作制作日志.我每天创建一个新文件,日期为文件名.现在,如果目录不存在,我希望系统为我创建目录.我搜索过这个主题,所有答案都是相同的:使用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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
错误信息:
mscorlib.dll中出现"System.IO.DirectoryNotFoundException"类型的异常,但未在用户代码中处理
附加信息:找不到路径'C:\ Users\***\Source\Repos\Project\ProjectName\Logs\WZCLogs\31032016.txt'的一部分.
suj*_*lil 17
该文件夹可能在您的C:\(安装操作系统的默认驱动器)中创建.那是文件夹的位置C:\Logs\WZCLogs\.您可以通过再次执行代码来确认在驱动器中的某个位置创建了文件夹,这次是if (!Directory.Exists(FilePath))返回true.由于您没有指定任何位置,因此编译器假定为So. 检查是否创建;
您可以扩展尝试像这样:
try
{
Directory.CreateDirectory(FilePath);
}
catch (Exception ex)
{
// handle them here
}
Run Code Online (Sandbox Code Playgroud)
如果路径是错误的,那么肯定会抛出异常; 我试过"X:\ sample",它给了我一个例外:
找不到路径'X:\ sample的一部分
好像我尝试Logs\WZCLogs了第一次不会给出任何例外,并且第二次跳过if; 因此我发现该文件夹是在其他地方创建的;
您可以进行这些更改以使其工作:
string FilePath=Path.Combine(HostingEnvironment.ApplicationPhysicalPath, @"Logs\WZCLogs");
Run Code Online (Sandbox Code Playgroud)
创建目录时需要使用绝对路径。请尝试以下操作:
private const string FilePath = "Logs/WZCLogs/";
public void MakeLog(string text)
{
string directory = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, FilePath);
Directory.CreateDirectory(directory); // no need to check if it exists
string logFile = Path.Combine(directory, DateTime.Now.ToString("ddMMyyyy") + ".txt");
if (!File.Exists(logFile))
{
FileStream f = File.Create(logFile);
f.Close();
}
using (StreamWriter sw = new StreamWriter(logFile, true))
{
sw.WriteLine(text);
sw.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
您不需要先检查目录是否存在,因为如果目录已经存在,则该CreateDirectory方法没有副作用。使用Path.Combine而不是直接连接字符串也是一种很好的做法,但要确保第二个参数不以斜杠开头。
您还可以通过使用该File.AppendAllText方法而不是创建FileStream.
private const string FilePath = "Logs/WZCLogs/";
public void MakeLog(string text)
{
string directory = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, FilePath);
Directory.CreateDirectory(directory);
string logFile = Path.Combine(directory, DateTime.Now.ToString("ddMMyyyy") + ".txt");
File.AppendAllText(logFile, text + Environment.NewLine);
}
Run Code Online (Sandbox Code Playgroud)