Skip to content

Instantly share code, notes, and snippets.

@Dkowald
Last active January 3, 2019 03:51
Show Gist options
  • Select an option

  • Save Dkowald/29f7577ab5155bbba0a9375d9cde37b1 to your computer and use it in GitHub Desktop.

Select an option

Save Dkowald/29f7577ab5155bbba0a9375d9cde37b1 to your computer and use it in GitHub Desktop.
Convert IFileInfo to FileInfo or DirectoryInfo objects.
using System;
using System.IO;
using Microsoft.Extensions.FileProviders;
// ReSharper disable once CheckNamespace
namespace kwd.gist
{
/// <summary>
/// Extensions to convert <see cref="IFileInfo"/> to
/// <see cref="FileInfo"/> and <see cref="DirectoryInfo"/> objects.
/// </summary>
public static class FileProviderConvertersExtensions
{
/// <summary>
/// Convert <see cref="IFileInfo"/> to <see cref="DirectoryInfo"/>
/// </summary>
/// <exception cref="NotPhysicalFile"></exception>
/// <exception cref="IsFile"></exception>
public static DirectoryInfo AsDirectory(this IFileInfo fileInfo)
{
if (fileInfo.PhysicalPath == null) { throw new NotPhysicalFile(); }
if (File.Exists(fileInfo.PhysicalPath)) { throw new IsDirectory(); }
return new DirectoryInfo(fileInfo.PhysicalPath);
}
/// <summary>
/// Try convert <see cref="IFileInfo"/> to <see cref="DirectoryInfo"/>.
/// </summary>
/// <returns>
/// <see cref="DirectoryInfo"/> or null.
/// </returns>
public static DirectoryInfo TryAsDirectory(this IFileInfo file)
=> file.PhysicalPath == null ||
File.Exists(file.PhysicalPath) ? null : new DirectoryInfo(file.PhysicalPath);
/// <summary>
/// Convert <see cref="IFileInfo"/> to <see cref="FileInfo"/>
/// </summary>
/// <exception cref="NotPhysicalFile"></exception>
/// <exception cref="IsDirectory"></exception>
public static FileInfo AsFile(this IFileInfo file)
{
if (file.PhysicalPath == null) { throw new NotPhysicalFile(); }
if (Directory.Exists(file.PhysicalPath)) { throw new IsFile(); }
return new FileInfo(file.PhysicalPath);
}
/// <summary>
/// Try convert <see cref="IFileInfo"/> to a <see cref="FileInfo"/>
/// </summary>
/// <returns>
/// <see cref="FileInfo"/> or null;
/// </returns>
public static FileInfo TryAsFile(this IFileInfo file) =>
file.PhysicalPath == null ||
Directory.Exists(file.PhysicalPath) ? null : new FileInfo(file.PhysicalPath);
}
public class NotPhysicalFile : Exception { }
public class IsDirectory : Exception { }
public class IsFile : Exception { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment