The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,649 other followers

.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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: