Convert file path to a file URI?

Viewed 241991

Does the .NET Framework have any methods for converting a path (e.g. "C:\whatever.txt") into a file URI (e.g. "file:///C:/whatever.txt")?

The System.Uri class has the reverse (from a file URI to absolute path), but nothing as far as I can find for converting to a file URI.

Also, this is not an ASP.NET application.

7 Answers

The workaround is simple. Just use the Uri().ToString() method and percent-encode white-spaces, if any, afterwards.

string path = new Uri("C:\my exampleㄓ.txt").ToString().Replace(" ", "%20");

properly returns file:///C:/my%20exampleㄓ.txt

Related