【问题标题】:Create directory if not exists如果不存在则创建目录
【发布时间】: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


【解决方案1】:

该文件夹可能会在您的C:\(安装操作系统的默认驱动器)中创建。也就是说文件夹位置是C:\Logs\WZCLogs\。您可以通过再次执行代码来确认在驱动器中的某处创建了一个文件夹,这次if (!Directory.Exists(FilePath)) 返回true。由于您没有指定任何位置,因此编译器假定为 So。检查是否创建;

你可以像这样扩展try:

try
{
    Directory.CreateDirectory(FilePath);
}
catch (Exception ex)
{
    // handle them here
}

如果路径错误,肯定会抛出异常;我尝试过使用“X:\sample”,这给了我一个例外:

找不到路径 'X:\sample

的一部分

而如果我尝试使用 Logs\WZCLogs 第一次不会给出任何异常,并且第二次也跳过 if;因此我发现该文件夹是在其他地方创建的;

您可以进行这些更改以使其正常工作:

 string FilePath=Path.Combine(HostingEnvironment.ApplicationPhysicalPath, @"Logs\WZCLogs");

【讨论】:

  • 这解决了我的问题,谢谢。将Directory.CreateDirectory(); 更改为Directory.CreateDirectory(HostingEnvironment.ApplicationPhysicalPath + FilePath);
  • // 创建指定路径下的所有目录和子目录,除非它们已经存在。 public static DirectoryInfo CreateDirectory(string path);
【解决方案2】:

创建目录时需要使用绝对路径。请尝试以下操作:

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();
     }
}

您不需要先检查目录是否存在,因为如果目录已经存在,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);
}

【讨论】:

    猜你喜欢
    • 2017-01-01
    • 1970-01-01
    • 2018-08-01
    • 2016-02-02
    • 2014-05-19
    • 2012-12-04
    • 2011-05-12
    相关资源
    最近更新 更多