简体   繁体   English

如何在C#中从单个完整路径创建多个目录?

[英]How to create multiple directories from a single full path in C#?

If you have a full path like: "C:\\dir0\\dir1\\dir2\\dir3\\dir4\\" how would you best implement it so that all directories are present? 如果你有一个完整的路径,如: "C:\\dir0\\dir1\\dir2\\dir3\\dir4\\"你将如何最好地实现它,以便所有目录都存在?

Is there a method for this in the BCL? 在BCL中有这种方法吗? If not, what's the most elegant way to do this? 如果没有,那么最优雅的方式是什么?

I would call Directory.CreateDirectory(@"C:\\dir0\\dir1\\dir2\\dir3\\dir4\\") . 我会调用Directory.CreateDirectory(@"C:\\dir0\\dir1\\dir2\\dir3\\dir4\\")

Contrary to popular belief, Directory.CreateDirectory will automatically create whichever parent directories do not exist. 与流行的看法相反, Directory.CreateDirectory将自动创建不存在的父目录。
In MSDN's words, Creates all directories and subdirectories as specified by path. 用MSDN的话来说, Creates all directories and subdirectories as specified by path.

If the entire path already exists, it will do nothing. 如果整个路径已经存在,它将什么都不做。 (It won't throw an exception) (它不会抛出异常)

Create directories from complete filepath 从完整文件路径创建目录

private String EvaluatePath(String path){

    try
    {
        String folder = Path.GetDirectoryName(path);
        if (!Directory.Exists(folder))
        {
            // Try to create the directory.
            DirectoryInfo di = Directory.CreateDirectory(folder);
        }
    }
    catch (IOException ioex)
    {
        Console.WriteLine(ioex.Message);
        return "";
    }
    return path;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SevenZipSharp-如何使用C#将多个目录压缩为单个文件? - SevenZipSharp - how to compress multiple directories into a single file using c#? c#如何从一段路径和文件名中获取完整路径 - How to get the full path from a segment of a path and the filename in c# 如何从C#的完整路径中获取一部分? - How to get a part from the full path in C#? 如何在 C# 中允许来自同一目录的单实例应用程序但来自不同目录的多个实例? - How to allow single instance application from the same directory but several instances from different directories in C#? 如何使用单个SQL字符串从C#中的多个表创建数据集? - How can I use a single SQL string to create a data-set from multiple tables in C#? 使用相同的C#源构建完整的.net,PCL和dotnet核心程序集的单个源项目? - Create a single source project with full .net, PCL and dotnet core assemblies build from same C# source? 从C#中的缩短路径获取完整路径 - Get full path from shortened path in C# 如何使用Path.GetFullPath在c#中获取文件完整路径 - How to get a file full path in c# with Path.GetFullPath 如何从 ZD7EFA19FBE7D3972FD7ZADB6024223D 中的 JSON 节点路径创建 JSON object - How to create JSON object from JSON node path in C# C#中文件夹的完整路径 - full path of a folder in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM