Last active
February 18, 2017 16:31
-
-
Save CallumWatkins/9b7c2a2ff260ee4eaf268db0de4d1211 to your computer and use it in GitHub Desktop.
Creates all directories and subdirectories unless they already exist and creates or overwrites a file in the specified path. License: MIT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
/// <summary> | |
/// Creates all directories and subdirectories unless they already exist and creates or overwrites a file in the specified path. | |
/// </summary> | |
/// <param name="path">The full path of the file.</param> | |
public static FileStream CreateFileAndDirectory(string path) | |
{ | |
if (path == null) { throw new ArgumentNullException(nameof(path)); } | |
if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentException("path cannot be empty."); } | |
string fileName = Path.GetFileName(path); | |
string directory = Path.GetDirectoryName(path); | |
return CreateFileAndDirectory(fileName, directory); | |
} | |
/// <summary> | |
/// Creates all directories and subdirectories unless they already exist and creates or overwrites a file in the same path. | |
/// </summary> | |
/// <param name="fileName">The name of the file.</param> | |
/// <param name="directory">The directory to create.</param> | |
public static FileStream CreateFileAndDirectory(string fileName, string directory) | |
{ | |
if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); } | |
if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentException("fileName cannot be empty."); } | |
if (directory == null) { throw new ArgumentNullException(nameof(directory)); } | |
if (string.IsNullOrWhiteSpace(directory)) { throw new ArgumentException("directory cannot be empty."); } | |
Directory.CreateDirectory(directory); | |
string path = directory + (directory.EndsWith("\\") ? string.Empty : "\\") + fileName; | |
return File.Create(path); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment