views:

293

answers:

3

What is the proper way to convert an XML URI into a Windows file path?

As a starting point, it's possible to turn:

file:///C:/DirA/DirB/File.txt

into:

C:\DirA\DirB\File.txt

... by first dropping the file:/// substring (having used it to determine we're dealing with a local file) and then placing a backslash wherever a slash appears in the original string. That seems like a good start, but it's not enough. For instance, the URI might look like this:

file:///C:/DirA/DirB/With%20Spaces.txt

... which becomes:

C:\DirA\DirB\With Spaces.txt

... after replacing %20s with spaces. Even that, however, would not be enough, as it may likewise be necessary to deal with other such encodings. Furthermore, some of those characters will not be legal Windows filename charcters, so it's necessary to identify which of those encodings are valid in Windows filenames and flag an error if anything else is encountered.

Is there anything else I'm forgetting? Anybody care to expand on the above?

+1  A: 

You should use PathCreateFromUrl() on Windows.

See also The Bizarre and Unhappy Story of File: URLs.

jeffamaphone
I was hoping for somebody to elaborate on the actual process of turning a URI into a Windows path, but under the circumstances I am marking your answer as accepted.
Adrian Lopez
+2  A: 

Use the Uri.LocalPath property.

string path = new Uri("file:///C:/folder/file.txt").LocalPath;

This is platform-senstive, so path is "C:\folder\file.txt" on my Windows machine.

Note that you can also go the other way (from a local file system path to a file URI) using the constructor:

var uri = new Uri(@"C:\folder\file.txt");
Pete Montgomery
A: 

WOW, such a simple method !