tags:

views:

201

answers:

4

i have a piece of code here that breaks if the directory doesn't exist

System.IO.File.WriteAllText(filePath, content);

is it possible to do in one line (or a few lines) to check the directory leading to the new file doesn't exist and if not, to create it before creating the new file.

i'm in .NET 3.5 here.

A: 

You can use File.Exists to check if the file exists and create it using File.Create if required.

Make sure you check if you have access to create files at that location.

Once you are certain that the file exists, you can write to it safely. Though as a precaution, you should put your code into a try...catch block and catch for the exceptions that function is likely to raise if things don't go exactly as planned.

Additional info for basic file IO concepts.

hitec
I initially mis-read your question that you wanted to write to a file that may not exist. The concepts are essentially the same for File and Directory IO though.
hitec
+1  A: 

(new FileInfo(filePath)).Directory.Create() Before writing to the file.

Or

System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);
Don
thanks, this is the solution i used!
RoboShop
+4  A: 

You can use following code

if (!Directory.Exists(path)) 
{
  DirectoryInfo di = Directory.CreateDirectory(path);
}
Ram
A: 

As @hitec said, you have to be sure that you have the right permissions, if you do, you can use this line to ensure the existence of the directory:

Directory.CreateDirectory(Path.GetDirectoryName(filePath))

willvv