How do I create a file AND any folders, if the folders don't exist?

C#.NetFile Access

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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!

Solution 3 - C#

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

Solution 4 - C#

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.

Solution 5 - C#

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

Solution 6 - C#

You should use Directory.CreateDirectory.

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

Solution 7 - C#

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] 3 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?

Solution 8 - C#

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

}

}

Solution 9 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPure.KromeView Question on Stackoverflow
Solution 1 - C#hultqvistView Answer on Stackoverflow
Solution 2 - C#Christopher B. AdkinsView Answer on Stackoverflow
Solution 3 - C#GrzenioView Answer on Stackoverflow
Solution 4 - C#OdedView Answer on Stackoverflow
Solution 5 - C#ArsenyView Answer on Stackoverflow
Solution 6 - C#NickView Answer on Stackoverflow
Solution 7 - C#PRRView Answer on Stackoverflow
Solution 8 - C#MarkiveView Answer on Stackoverflow
Solution 9 - C#Mehdi DehghaniView Answer on Stackoverflow