Skip to content

Instantly share code, notes, and snippets.

@wolf99
Created August 9, 2017 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolf99/c2e9f9a445126fdb7e60858e03d5ccdd to your computer and use it in GitHub Desktop.
Save wolf99/c2e9f9a445126fdb7e60858e03d5ccdd to your computer and use it in GitHub Desktop.
method to convert a file path to a URI
// 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