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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2134392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:47:00  来源:igfitidea点击:

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

c#.netbase-class-library

提问by Joan Venge

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? If not, what's the most elegant way to do this?

BCL中是否有这种方法?如果不是,那么最优雅的方法是什么?

采纳答案by SLaks

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

我会打电话给Directory.CreateDirectory(@"C:\dir0\dir1\dir2\dir3\dir4\")

Contrary to popular belief, Directory.CreateDirectorywill automatically create whichever parent directories do not exist.
In MSDN's words, Creates all directories and subdirectories as specified by path.

与流行的看法相反,Directory.CreateDirectory将自动创建不存在的父目录。
用 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)

如果整个路径已经存在,它将什么都不做。(它不会抛出异常)

回答by Alejandro Aranda

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