.NET/C# – How to create a file and its parent directories in one method call? (via: Stack Overflow)
Posted by jpluimers on 2012/12/18
Ever since .NET 1 there has been no built-in way to create a file including all its parent directories.
Hence small FileHelper class far below.
The fundament of the class is this CreateUnderlyingDirectory method, that uses System.IO.Path.GetDirectoryName to obtain the parent directory of a path, and then System.IO.Directory.CreateDirectory to create it (and any parent directories) if needed.
public static void CreateUnderlyingDirectory(string path)
{
string directoryPath = Path.GetDirectoryName(path);
Directory.CreateDirectory(directoryPath); // NOP if it exists, will create all parent directories if not
}
A few helper methods get you a StreamWriter either empty/appended, or always empty.
using System.IO;
namespace BeSharp.IO
{
public static class FileHelper
{
public static void CreateUnderlyingDirectory(string path)
{
string directoryPath = Path.GetDirectoryName(path);
Directory.CreateDirectory(directoryPath); // NOP if it exists, will create all parent directories if not
}
public static StreamWriter AppendTextOrCreateTextAndParentDirectories(string path)
{
StreamWriter result;
if (File.Exists(path))
{
result = File.AppendText(path);
}
else
{
CreateUnderlyingDirectory(path);
result = File.CreateText(path);
}
return result;
}
public static StreamWriter CreateOrOverwriteTextAndCreateParentDirectories(string path)
{
CreateUnderlyingDirectory(path);
StreamWriter result = new StreamWriter(path, false);
return result;
}
}
}
–jeroen
via: c# – How to create a file and its parent directories in one method call? – Stack Overflow.






Leave a comment