Skip to content

Instantly share code, notes, and snippets.

@rquackenbush
Created May 1, 2017 17:42
Show Gist options
  • Save rquackenbush/efe306bd18417a03b9b9c1184647dfc0 to your computer and use it in GitHub Desktop.
Save rquackenbush/efe306bd18417a03b9b9c1184647dfc0 to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.IO;
namespace Stuff
{
public static class FileUtilities
{
/// <summary>
/// Will attempt to create the path for a file if it doesn't exist
/// </summary>
/// <param name="path"></param>
public static void CreateDirectoryForFile(string path)
{
var directory = Path.GetDirectoryName(path);
if (!string.IsNullOrWhiteSpace(directory))
{
Directory.CreateDirectory(directory);
}
}
/// <summary>
/// Gets the fully qualified path given a filename and a relative path.
/// </summary>
/// <param name="filename">A fully qualified path to a file.</param>
/// <param name="relativePath">A relative path to a file.</param>
/// <returns></returns>
public static string GetFullyQualifiedPath(string filename, string relativePath)
{
var baseDirectory = new FileInfo(filename).DirectoryName;
if (string.IsNullOrEmpty(baseDirectory) || string.IsNullOrEmpty(relativePath))
return null;
return Path.Combine(baseDirectory, relativePath);
}
public static string GetRelativePath(string baseDirectory, string filename)
{
if (!baseDirectory.EndsWith("\\"))
baseDirectory += "\\";
Uri file = new Uri(filename);
// Must end in a slash to indicate folder
Uri folder = new Uri(baseDirectory);
return Uri.UnescapeDataString(folder.MakeRelativeUri(file)
.ToString()
.Replace('/', Path.DirectorySeparatorChar)
);
}
/// <summary>
/// Opens a file location. Very snazzy.
/// </summary>
/// <param name="path"></param>
public static void OpenFileLocation(string path)
{
// http://stackoverflow.com/a/9646139/232566
if (File.Exists(path))
{
Process.Start("explorer.exe", $"/select, {path}");
}
}
/// <summary>
/// If the file exists, returns the contents. Otherwise, returns null.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string TryReadAllText(string path)
{
if (File.Exists(path))
return File.ReadAllText(path);
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment