【问题标题】:make sure folder exist before create file inside this folder [duplicate]在此文件夹内创建文件之前确保文件夹存在[重复]
【发布时间】:2012-10-17 13:47:56
【问题描述】:

可能重复:
C# Check if folder exist in directory and create them

我有创建文件并需要将它们放在特定文件夹中的应用程序,检查文件夹是否存在以及不创建文件夹的最佳解决方案是什么? (我是新开发者)

【问题讨论】:

标签: c#


【解决方案1】:

Directory.Exists Method。这是给你的示例代码。

string path = @"C:\MyFolder";
if(!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}

这个方法在System.IO命名空间中

【讨论】:

    【解决方案2】:

    试试这个

    if(System.IO.Directory.Exists("c:\\temp"))
    {
       //Folder exists
    }
    else
    {
        //Folder does not exist
    }
    

    【讨论】:

    • 如果这个文件夹不存在?
    【解决方案3】:

    只需调用

    Directory.CreateDirectory(path);
    

    它会检查目录是否存在,如果存在则什么都不做。因此,根本不需要使用Directory.Exists() 进行事先检查。

    另见this answer

    【讨论】:

      【解决方案4】:

      查看Directory.Exists() 方法。 MSDN doc here

      string path = "c:\\MyDirectory";
      
      if (!Directory.Exists( path )) {
          DirectoryInfo di = Directory.CreateDirectory(path);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-10
        • 2018-11-28
        • 1970-01-01
        • 2013-06-24
        • 2013-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多