Last active
January 3, 2019 03:51
-
-
Save Dkowald/29f7577ab5155bbba0a9375d9cde37b1 to your computer and use it in GitHub Desktop.
Convert IFileInfo to FileInfo or DirectoryInfo objects.
This file contains hidden or 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; | |
| 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