Last active
May 24, 2017 08:24
-
-
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
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
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