Skip to content

Instantly share code, notes, and snippets.

@shaybensasson
Created May 29, 2015 06:18
Show Gist options
  • Select an option

  • Save shaybensasson/5044aa9e0e97b5bc7c77 to your computer and use it in GitHub Desktop.

Select an option

Save shaybensasson/5044aa9e0e97b5bc7c77 to your computer and use it in GitHub Desktop.
Validates and cleans invalid path and filenames
using System;
using System.IO;
using System.Text.RegularExpressions;
namespace WallpaperFromRSS
{
public static class PathValidation
{
private static readonly string pathValidatorExpression = "^[^" + string.Join("", Array.ConvertAll(Path.GetInvalidPathChars(), x => Regex.Escape(x.ToString()))) + "]+$";
private static readonly Regex pathValidator = new Regex(pathValidatorExpression, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly string fileNameValidatorExpression = "^[^" + string.Join("", Array.ConvertAll(Path.GetInvalidFileNameChars(), x => Regex.Escape(x.ToString()))) + "]+$";
private static readonly Regex fileNameValidator = new Regex(fileNameValidatorExpression, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly string pathCleanerExpression = "[" + string.Join("", Array.ConvertAll(Path.GetInvalidPathChars(), x => Regex.Escape(x.ToString()))) + "]";
private static readonly Regex pathCleaner = new Regex(pathCleanerExpression, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly string fileNameCleanerExpression = "[" + string.Join("", Array.ConvertAll(Path.GetInvalidFileNameChars(), x => Regex.Escape(x.ToString()))) + "]";
private static readonly Regex fileNameCleaner = new Regex(fileNameCleanerExpression, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);
public static bool ValidatePath(string path)
{
return pathValidator.IsMatch(path);
}
public static bool ValidateFileName(string fileName)
{
return fileNameValidator.IsMatch(fileName);
}
public static string CleanPath(string path)
{
return pathCleaner.Replace(path, "");
}
public static string CleanFileName(string fileName)
{
return fileNameCleaner.Replace(fileName, "");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment