如果文件夹不存在,如何创建文件和文件夹?

发布于 2024-09-08 18:37:40 字数 587 浏览 6 评论 0原文

想象一下,我希望创建(或覆盖)以下文件:- C:\Temp\Bar\Foo\Test.txt

使用 File.Create(..) 方法,这个可以做到。

但是,如果我没有以下任一文件夹(来自上面的示例路径)

  • Temp
  • Bar
  • Foo

,那么我会得到一个 DirectoryNotFoundException 抛出。

所以..给定一个路径,我们如何递归地创建为该路径创建文件..所需的所有文件夹?如果 Temp 或 Bar 文件夹存在,但 Foo 不存在...那么也被创建。

为了简单起见,我们假设没有安全问题——所有权限都很好,等等。

Imagine I wish to create (or overwrite) the following file :- C:\Temp\Bar\Foo\Test.txt

Using the File.Create(..) method, this can do it.

BUT, if I don't have either one of the following folders (from that example path, above)

  • Temp
  • Bar
  • Foo

then I get an DirectoryNotFoundException thrown.

So .. given a path, how can we recursively create all the folders necessary to create the file .. for that path? If Temp or Bar folders exists, but Foo doesn't... then that is created also.

For simplicity, lets assume there's no Security concerns -- all permissions are fine, etc.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

孤独难免 2024-09-15 18:37:40

总结其他答案中评论的内容:

//path = @"C:\Temp\Bar\Foo\Test.txt";
Directory.CreateDirectory(Path.GetDirectoryName(path));

Directory.CreateDirectory 将递归地创建目录,如果目录已经存在,它将返回而不会出现错误。

如果 C:\Temp\Bar\Foo 处恰好有一个文件 Foo,则会抛出异常。

To summarize what has been commented in other answers:

//path = @"C:\Temp\Bar\Foo\Test.txt";
Directory.CreateDirectory(Path.GetDirectoryName(path));

Directory.CreateDirectory will create the directories recursively and if the directory already exist it will return without an error.

If there happened to be a file Foo at C:\Temp\Bar\Foo an exception will be thrown.

凉薄对峙 2024-09-15 18:37:40
DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.",
    Directory.GetCreationTime(path));

请参阅此 MSDN 页面

DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.",
    Directory.GetCreationTime(path));

See this MSDN page.

泛泛之交 2024-09-15 18:37:40

使用 Directory.CreateDirectory在创建文件之前。它会为您递归地创建文件夹。

Use Directory.CreateDirectory before you create the file. It creates the folder recursively for you.

临走之时 2024-09-15 18:37:40

。给定一个路径,我们如何递归地创建为该路径创建文件..所需的所有文件夹

创建路径指定的所有目录和子目录。

Directory.CreateDirectory(path);

然后你可以创建一个文件。

. given a path, how can we recursively create all the folders necessary to create the file .. for that path

Creates all directories and subdirectories as specified by path.

Directory.CreateDirectory(path);

then you may create a file.

心意如水 2024-09-15 18:37:40

您需要检查路径的两个部分(目录和文件名),如果不存在则创建每个部分。

使用File.ExistsDirectory.Exists来查明它们是否存在。 Directory.CreateDirectory 将为您创建整个路径,因此如果目录不存在,您只需调用一次,然后只需创建文件即可。

You will need to check both parts of the path (directory and filename) and create each if it does not exist.

Use File.Exists and Directory.Exists to find out whether they exist. Directory.CreateDirectory will create the whole path for you, so you only ever need to call that once if the directory does not exist, then simply create the file.

予囚 2024-09-15 18:37:40

您应该使用 Directory.CreateDirectory。

http://msdn.microsoft.com/en-us/library/54a0at6s。 ASPX

You should use Directory.CreateDirectory.

http://msdn.microsoft.com/en-us/library/54a0at6s.aspx

情域 2024-09-15 18:37:40

假设您的程序集/exe 具有 FileIO许可本身就是不对的。您的应用程序可能无法以管理员权限运行。重要的是要考虑代码访问安全和< a href="http://support.microsoft.com/kb/842419" rel="nofollow noreferrer">请求 权限
示例代码:

FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read, "C:\\test_r");
f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");
try
{
    f2.Demand();
}
catch (SecurityException s)
{
    Console.WriteLine(s.Message);
}

了解 .NET 代码访问安全性

“代码访问安全性”在现实世界中有用吗?

Assuming that your assembly/exe has FileIO permission is itself, well is not right. Your application may not run with admin rights. Its important to consider Code Access Security and requesting permissions
Sample code:

FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read, "C:\\test_r");
f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");
try
{
    f2.Demand();
}
catch (SecurityException s)
{
    Console.WriteLine(s.Message);
}

Understanding .NET Code Access Security

Is “Code Access Security” of any real world use?

彡翼 2024-09-15 18:37:40

你想要 Directory.CreateDirectory()

这里是我使用的一个类(转换为 C#),如果你向它传递一个源目录和一个目标,它将将该目录的所有文件和子文件夹复制到你的目标:

using System.IO;

public class copyTemplateFiles
{


public static bool Copy(string Source, string destination)
{

    try {

        string[] Files = null;

        if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) {
            destination += Path.DirectorySeparatorChar;
        }

        if (!Directory.Exists(destination)) {
            Directory.CreateDirectory(destination);
        }

        Files = Directory.GetFileSystemEntries(Source);
        foreach (string Element in Files) {
            // Sub directories
            if (Directory.Exists(Element)) {
                copyDirectory(Element, destination + Path.GetFileName(Element));
            } else {
                // Files in directory
                File.Copy(Element, destination + Path.GetFileName(Element), true);
            }
        }

    } catch (Exception ex) {
        return false;
    }

    return true;

}



private static void copyDirectory(string Source, string destination)
{
    string[] Files = null;

    if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) {
        destination += Path.DirectorySeparatorChar;
    }

    if (!Directory.Exists(destination)) {
        Directory.CreateDirectory(destination);
    }

    Files = Directory.GetFileSystemEntries(Source);
    foreach (string Element in Files) {
        // Sub directories
        if (Directory.Exists(Element)) {
            copyDirectory(Element, destination + Path.GetFileName(Element));
        } else {
            // Files in directory
            File.Copy(Element, destination + Path.GetFileName(Element), true);
        }
    }

}

}

You want Directory.CreateDirectory()

Here is a class I use (converted to C#) that if you pass it a source directory and a destination it will copy all of the files and sub-folders of that directory to your destination:

using System.IO;

public class copyTemplateFiles
{


public static bool Copy(string Source, string destination)
{

    try {

        string[] Files = null;

        if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) {
            destination += Path.DirectorySeparatorChar;
        }

        if (!Directory.Exists(destination)) {
            Directory.CreateDirectory(destination);
        }

        Files = Directory.GetFileSystemEntries(Source);
        foreach (string Element in Files) {
            // Sub directories
            if (Directory.Exists(Element)) {
                copyDirectory(Element, destination + Path.GetFileName(Element));
            } else {
                // Files in directory
                File.Copy(Element, destination + Path.GetFileName(Element), true);
            }
        }

    } catch (Exception ex) {
        return false;
    }

    return true;

}



private static void copyDirectory(string Source, string destination)
{
    string[] Files = null;

    if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) {
        destination += Path.DirectorySeparatorChar;
    }

    if (!Directory.Exists(destination)) {
        Directory.CreateDirectory(destination);
    }

    Files = Directory.GetFileSystemEntries(Source);
    foreach (string Element in Files) {
        // Sub directories
        if (Directory.Exists(Element)) {
            copyDirectory(Element, destination + Path.GetFileName(Element));
        } else {
            // Files in directory
            File.Copy(Element, destination + Path.GetFileName(Element), true);
        }
    }

}

}

〗斷ホ乔殘χμё〖 2024-09-15 18:37:40

以下代码将创建目录(如果不存在)&然后复制文件

// using System.IO;

// for ex. if you want to copy files from D:\A\ to D:\B\
foreach (var f in Directory.GetFiles(@"D:\A\", "*.*", SearchOption.AllDirectories))
{
    var fi =  new FileInfo(f);
    var di = new DirectoryInfo(fi.DirectoryName);

    // you can filter files here
    if (fi.Name.Contains("FILTER")
    {
        if (!Directory.Exists(di.FullName.Replace("A", "B"))
        {                       
            Directory.CreateDirectory(di.FullName.Replace("A", "B"));           
            File.Copy(fi.FullName, fi.FullName.Replace("A", "B"));
        }
    }
}

Following code will create directories (if not exists) & then copy files.

// using System.IO;

// for ex. if you want to copy files from D:\A\ to D:\B\
foreach (var f in Directory.GetFiles(@"D:\A\", "*.*", SearchOption.AllDirectories))
{
    var fi =  new FileInfo(f);
    var di = new DirectoryInfo(fi.DirectoryName);

    // you can filter files here
    if (fi.Name.Contains("FILTER")
    {
        if (!Directory.Exists(di.FullName.Replace("A", "B"))
        {                       
            Directory.CreateDirectory(di.FullName.Replace("A", "B"));           
            File.Copy(fi.FullName, fi.FullName.Replace("A", "B"));
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文