views:

112

answers:

7

Hi folks,

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.

+1  A: 

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.

Oded
For Directory.CreateDirectory you do not need to see which part exists. It will create all directories needed (only thing to make sure is that the targeted directory does not exists already).
Gertjan
@Gertjan - thanks for your input. Answer clarified.
Oded
@Oded, I suggest removing the first line of you answer in that case since he doesn't need to check for each part from the root, just check the complete path and create it if it does not exist.
Gertjan
@Gertjan - answer updated... hope it meets your standards now ;)
Oded
:) it does :)(it was not my point to prove you wrong or to offend you, but beginners can use any clarification in the answers)
Gertjan
+2  A: 

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

Grzenio
+1  A: 

You should use Directory.CreateDirectory.

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

Nick
*Remarks: Any and all directories specified in path are created* ... ahh kewl! cheers :)
Pure.Krome
+1  A: 

. 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.

Arseny
+4  A: 
// Determine whether the directory exists.
if (Directory.Exists(path)) 
{
    Console.WriteLine("That path exists already.");
    return;
}

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

See this MSDN page.

Hope that helps out!

Adkins
You can blindly call `Directory.CreateDirectory` without the `Directory.Exists` check first - it won't throw if the directory is already there.
Tim Robinson
@Tim: Wasn't sure so I threw it in there anywho. Thanks for the info though.
Adkins
And don't forget about [`Path.GetDirectoryName(string path)`](http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname.aspx) to get the directory from your full path
Oliver
@Oliver: There is a whole slew of functionality that goes along with the Directory and DirectoryInfo classes, but the code I gave was enough to give him a push in the right direction. I think the link also expands quite a bit.
Adkins
A: 

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

}

}

Markive
I should downgrade this because of this line: `using Microsoft.VisualBasic;` Evil!!
Pure.Krome
Haha, sorry I didn't fully check it just stuck it in a converter.. my bad..
Markive
And why is Microsoft.VisualBasic evil?? It's an assembly like anyone else in the .Net Framework.
Oliver
I suppose because your importing the namespace of a whole other language unnecessarily..?
Markive
A: 

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?

PRR
Heh - dude. I only said that so this questions didn't get too complex and over take the core of my question. I never asserted that i shouldn't worry about permissions .. just not to add extra complexity to the question and thus any answers.
Pure.Krome
@Pure.Krome: Although my answer is off target, still do consider security and access control when accessing privileged resource. Never meant to overtake or complicate your question :)
PRR