Automatically create directories from long paths
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?
foreach (var relativePath in files.Keys)
{
var fullPath = Path.Combine(defaultLocation, relativePath);
var directory = Path.GetDirectoryName(fullPath);
Directory.CreateDirectory(directory);
saveFile(fullPath, files[relativePath]);
}
where files is IDictionary<string, object>
.
string somepath = @"z:/root/test/thing1/thing2/file.txt";
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName( ( somepath ) );
Directory.CreateDirectory("/root/...")
Creates all directories and subdirectories in the specified path
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);
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.
I've found setting the "default location" at the start of execution to be helpful and reduce a bit of redundant code (e.g., Path.Combine(defaultLocation, relativePath)
).
Example:
var defaultLocation = "z:/";
Directory.SetCurrentDirectory(defaultLocation);
Directory.SetCurrentDirectory(AppContext.BaseDirectory);
精彩评论