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?
Automatically create directories from long paths
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 ) );
The create Directory.CreateDirectory(somepath) method creates all directories and subdirectories for you –
Cralg
Directory.CreateDirectory("/root/...")
Creates all directories and subdirectories in the specified path
Agreed, no need to check if directory exists as it does this internally. –
Teresitateressa
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);
© 2022 - 2024 — McMap. All rights reserved.