85 lines
2.6 KiB
C#
85 lines
2.6 KiB
C#
using System.Text;
|
|
|
|
namespace Core.Helpers;
|
|
|
|
/// <summary>
|
|
/// Provides some path-related actions
|
|
/// </summary>
|
|
public static class PathHelper
|
|
{
|
|
/// <summary>
|
|
/// Verifies the existence of a path
|
|
/// </summary>
|
|
/// <param name="path">Path to check</param>
|
|
/// <exception cref="FileNotFoundException">If the given path does not exist</exception>
|
|
public static void CheckPathValidity(string path)
|
|
{
|
|
if (!File.Exists(path)) throw new FileNotFoundException($"Could not found file at {path}");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Create a file and all its parents directories if the file does not exists
|
|
/// </summary>
|
|
/// <param name="path"></param>
|
|
public static void CreateFileIfNotExists(string path)
|
|
{
|
|
if (!File.Exists(path)) Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Extracts raw text from a file references by given path
|
|
/// </summary>
|
|
/// <param name="path">Location of file</param>
|
|
/// <returns>Raw text</returns>
|
|
/// <exception cref="FileNotFoundException">If the given path does not exist</exception>
|
|
public static string TextFrom(string path)
|
|
{
|
|
CheckPathValidity(path);
|
|
return File.ReadAllText(path);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get the folder containing the last item of a given path
|
|
///
|
|
/// </summary>
|
|
/// <param name="path">The given path</param>
|
|
/// <returns>The folder containing the last element of the given path</returns>
|
|
public static string GetFolder(string path)
|
|
{
|
|
path = path.Replace("\\", "/");
|
|
var s = path.Split("/").ToList();
|
|
s.RemoveAt(s.Count-1);
|
|
var r = string.Join("/", s) + "/";
|
|
return r;
|
|
}
|
|
|
|
public static string GetName(string path)
|
|
{
|
|
return path.Split("/")[0];
|
|
}
|
|
|
|
/// <summary>
|
|
/// Concatenates a string representing the path of a folder and a string representing a file name
|
|
/// The strings come from default arguments.
|
|
/// </summary>
|
|
/// <returns>Concatenated path</returns>
|
|
public static string FullPath(params string[] pathItems)
|
|
{
|
|
StringBuilder builder = new StringBuilder();
|
|
foreach (var pi in pathItems)
|
|
{
|
|
builder.Append(pi);
|
|
}
|
|
return AbsolutePath(builder.ToString());
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns the absolute path based on a relative path
|
|
/// </summary>
|
|
/// <param name="relative">relative path</param>
|
|
/// <returns>Absolute path as string</returns>
|
|
public static string AbsolutePath(string relative)
|
|
{
|
|
return Path.GetFullPath(relative);
|
|
}
|
|
} |