I have a collection of files with fully qualified paths (root/test/thing1/thing2/file.txt). I want to foreach
over this collection and drop the file into the location defined in the path, however, if certain directories don't exist, I want them to great created automatically. My program has a default "drop location", such as z:/
. The "drop location" starts off empty, so in my example above, the first item should automatically create the directories needed to create z:/root/test/thing1/thing2/file.txt
. How can I do this?
views:
59answers:
5
A:
string somepath = @"z:/root/test/thing1/thing2/file.txt";
Directory.CreateDirectory( Path.GetDirectoryName( somepath ) );
Joel Lucsy
2010-10-27 19:20:33
A:
Check IO namespace (Directory, Path), I think they'll help you
using System.IO
Then check it..
string fileName =@"d:/root/test/thing1/thing2/file.txt";
string directory = Path.GetDirectoryName(fileName);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
Homam
2010-10-27 19:21:17
+1
A:
Directory.CreateDirectory("/root/...")
Creates all directories and subdirectories in the specified path
A_Nablsi
2010-10-27 19:21:50
Agreed, no need to check if directory exists as it does this internally.
Squirrel
2010-10-27 20:14:51
+5
A:
foreach (string sRelativePath in dicFiles.Keys)
{
string sFullPath = Path.Combine(sDefaultLocation, sRelativePath);
string sDirectory = Path.GetDirectoryName(sFullPath);
Directory.CreateDirectory(sDirectory);
saveFile(sFullPath, dicFiles[sRelativePath]);
}
where dicFiles is something like a Dictionary<string, object>
.
GCATNM
2010-10-27 19:21:56
A:
string filename = "c:\\temp\\wibble\\wobble\\file.txt";
string dir = Path.GetDirectoryName(filename);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.Create(filename);
with suitable exception handling, of course.
Steve Townsend
2010-10-27 19:24:42