using System; using System.IO; using System.Security; namespace EmbedIO.Utilities { partial class Validate { private static readonly char[] InvalidLocalPathChars = GetInvalidLocalPathChars(); /// /// Ensures that the value of an argument is a valid URL path /// and normalizes it. /// /// The name of the argument to validate. /// The value to validate. /// If set to true, the returned path /// is ensured to end in a slash (/) character; otherwise, the returned path is /// ensured to not end in a slash character unless it is "/". /// The normalized URL path. /// is . /// /// is empty. /// - or - /// does not start with a slash (/) character. /// /// public static string UrlPath(string argumentName, string value, bool isBasePath) { var exception = Utilities.UrlPath.ValidateInternal(argumentName, value); if (exception != null) throw exception; return Utilities.UrlPath.Normalize(value, isBasePath); } /// /// Ensures that the value of an argument is a valid local path /// and, optionally, gets the corresponding full path. /// /// The name of the argument to validate. /// The value to validate. /// to get the full path, to leave the path as is.. /// The local path, or the full path if is . /// is . /// /// is empty. /// - or - /// contains only white space. /// - or - /// contains one or more invalid characters. /// - or - /// is and the full path could not be obtained. /// public static string LocalPath(string argumentName, string value, bool getFullPath) { if (value == null) throw new ArgumentNullException(argumentName); if (value.Length == 0) throw new ArgumentException("Local path is empty.", argumentName); if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("Local path contains only white space.", argumentName); if (value.IndexOfAny(InvalidLocalPathChars) >= 0) throw new ArgumentException("Local path contains one or more invalid characters.", argumentName); if (getFullPath) { try { value = Path.GetFullPath(value); } catch (Exception e) when (e is ArgumentException || e is SecurityException || e is NotSupportedException || e is PathTooLongException) { throw new ArgumentException("Could not get the full local path.", argumentName, e); } } return value; } private static char[] GetInvalidLocalPathChars() { var systemChars = Path.GetInvalidPathChars(); var p = systemChars.Length; var result = new char[p + 2]; Array.Copy(systemChars, result, p); result[p++] = '*'; result[p] = '?'; return result; } } }