Skip to content

Instantly share code, notes, and snippets.

@solrevdev
Last active May 24, 2017 08:24
Show Gist options
  • Save solrevdev/afd80a022d5d22d396927297e7a0a601 to your computer and use it in GitHub Desktop.
Save solrevdev/afd80a022d5d22d396927297e7a0a601 to your computer and use it in GitHub Desktop.
GetSafePath - given any path from any OS remove illegal characters and use the current OS Directory Seperator Char
public static string GetSafePath(string filePath)
{
if (string.IsNullOrEmpty(filePath)) return string.Empty;
//Strip invalid chars
foreach (var invalidChar in Path.GetInvalidPathChars())
{
filePath = filePath.Replace(invalidChar.ToString(), String.Empty);
}
return filePath
.TrimStart('.', '/', '\\') //Remove illegal chars at the start
.Replace('\\', '/') //Switch all to use the same seperator
.Replace("../", string.Empty) //Remove access to top-level directories anywhere else
.Replace('/', Path.DirectorySeparatorChar); //Switch all to use the OS seperator
}
public static string AnotherWay()
{
Console.WriteLine("..{0}Data{0}uploads{0}{{filename}}", Path.DirectorySeparatorChar);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment