tags:

views:

3264

answers:

2

I have a use cases where I will be dealing with both local file paths (e.g. c:\foo\bar.txt) and URI's (e.g. http://somehost.com/fiz/baz). I also will be dealing with both relative and absolute paths so I need functionality like Path.Combine and friends.

Is there an existing C# type I should use? The Uri type might work but at a passing glance, it seems to be URI only.

+7  A: 

Using the Uri class, it seems to be working. It turns any file path to the `file:///..." syntax in the Uri. It handles any URI as expected, and it has capacity to deal with relative URIs. It depends on what else you are trying to do with that path.

(Updated to show the use of relative Uri's):

        string fileName = @"c:\temp\myfile.bmp";
        string relativeFile = @".\woohoo\temp.bmp";
        string addressName = @"http://www.google.com/blahblah.html";

        Uri uriFile = new Uri(fileName);
        Uri uriRelative = new Uri(uriFile, relativeFile);
        Uri uriAddress = new Uri(addressName);

        Console.WriteLine(uriFile.ToString());
        Console.WriteLine(uriRelative.ToString());
        Console.WriteLine(uriAddress.ToString());

Gives me this output:

file:///c:/temp/myfile.bmp
file:///c:/temp/woohoo/temp.bmp
http://www.google.com/blahblah.html

Erich Mirabal
that file:/// thing is... inconvenient, but I can live with it if I must. I was really hoping for something more directly set up for it +1
BCS
Well, you can inspect the "LocalPath" property, which will give you the filename in local format (without the file:///).
Erich Mirabal
Very helpful! Thanks for the quick answer.
Robert Williams
A: 

I hope I'm wrong here, but it seems to me that the Uri class can only handle absolute URLs? For example, a relative path to an ftp file is not supported. Was this not part of the question?

I guess the problem is that URL syntax itself actually doesn't support it, e.g. ftp://ftp.example.com/dir/file.py Where "dir/file.py" is always interpreted as residing in the root of the ftp server, which might of course be incorrect. The syntax used by e.g. scp supports relative syntax, like so: [email protected]:dir/file.py, which correctly points to "dir/file.py" relative to the home dir. But that syntax isn't supported by the Uri class, or is there a class that can hold this information? I don't think the proposed (and accepted) answer really answered the question posed.

André