Created
August 9, 2017 14:51
-
-
Save wolf99/c2e9f9a445126fdb7e60858e03d5ccdd to your computer and use it in GitHub Desktop.
method to convert a file path to a URI
This file contains 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
// The System.Uri class can convert paths to URIs using new Uri(pathString).AbsoluteUri; | |
// However, that does not work if the path contains some characters, e.g. the percent | |
// sign or spaces. This method corrects that, it is taken from, explained and MIT | |
// licensed, here: https://stackoverflow.com/a/35734486/1292918 | |
public static string FilePathToFileUrl(string filePath) | |
{ | |
StringBuilder uri = new StringBuilder(); | |
foreach (char v in filePath) | |
{ | |
if ((v >= 'a' && v <= 'z') || (v >= 'A' && v <= 'Z') || (v >= '0' && v <= '9') || | |
v == '+' || v == '/' || v == ':' || v == '.' || v == '-' || v == '_' || v == '~' || | |
v > '\xFF') | |
{ | |
uri.Append(v); | |
} | |
else if (v == Path.DirectorySeparatorChar || v == Path.AltDirectorySeparatorChar) | |
{ | |
uri.Append('/'); | |
} | |
else | |
{ | |
uri.Append(String.Format("%{0:X2}", (int)v)); | |
} | |
} | |
if (uri.Length >= 2 && uri[0] == '/' && uri[1] == '/') // UNC path | |
uri.Insert(0, "file:"); | |
else | |
uri.Insert(0, "file:///"); | |
return uri.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment