【问题标题】:CreatDirectory or Delete directory is slower than code创建目录或删除目录比代码慢
【发布时间】:2019-08-19 08:19:05
【问题描述】:

如果您能帮助我,请提出一个简短的问题。 在 C# 中,我正在创建一个目录,如果它不存在的话。在下一个命令中,我正在检查目录是否存在,我将复制一些文件。

问题是,创建新目录或删除它需要时间并且比下一个代码执行时间慢。

软件报错“文件夹不存在”。 在将内容复制到目录之前,我使用Thread.Sleep(5000); 等待 5 秒钟。

它似乎正在工作,但我觉得这不是应该的方式。有人知道更好的编码吗?

string logDirectoryPath = Directory.GetCurrentDirectory() + "\\LogFiles";
if (!Directory.Exists(logDirectoryPath))
{
   Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\LogFiles");
   Thread.Sleep(5000);
}

if (Directory.Exists(Directory.GetCurrentDirectory() + "\\LogFiles"))
{
   var s = logDirectoryPath + "\\Log_" + DateTime.Now.ToString("dd_MM_yyyy") + ".txt";

   using (StreamWriter w = File.AppendText(s))
   {
      w.WriteLine("--");
      w.Write("\r\nLog Entry : ");
      w.WriteLine($"{DateTime.Now.ToLongTimeString()} {DateTime.Now.ToLongDateString()}");
   }
}

//编辑 只是想也许我应该使用循环?

While(!Directory.Exists(logDirectoryPath))
{
      Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\LogFiles");
}

【问题讨论】:

  • hrmm,显然Directory.CreateDirectory 会在下一行代码执行之前创建目录。这个故事还有更多内容
  • 你的代码对我有用。
  • 请提供您的问题的minimal reproducible example

标签: c# system.io.file


【解决方案1】:

使用目录信息

DirectoryInfo di = new DirectoryInfo(#{PATHSTRING});

并使用 di.Exists 来检查它是否存在 / di.Create() 来创建文件夹

我想推荐使用您已经定义的 logDirectoryPath。

喜欢这个

DirectoryInfo di = new DirectoryInfo(logDirectoryPath);

if ( !di.Exists ) {
    di.Create();
}

【讨论】:

  • 你好阿菲尔。感谢你的回复。我不明白。似乎类似的代码和 DirectoryInfo 比 Directory 快吗?因为我的问题是,在创建目录之前,下一个代码检查是创建的目录。
  • 如果这段代码也有问题,请尝试使用 async/await 函数等待您的目录创建。
猜你喜欢
  • 2016-06-14
  • 1970-01-01
  • 2012-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多