2

I think I'm missing something obvious....

I've been reading code in a new project and have encountered code equivalent to the following:

var filePath = @"C:\temp\tmp1234.tmp";    // Generally obtained from System.IO.* calls
var uri = new Uri("file://" + filePath);

I thought that would be equivalent to:

var filePath = @"C:\temp\tmp1234.tmp";
var uri = new Uri(filePath);

(assuming the Uri class can parse the file path, deduce the scheme and do whatever escaping needs doing).

Since the code seems to work and this being done so frequently and so consistently I'm assuming the original developer had a good reason for using the "file://" + filePath idiom. Could someone clue me in about what that reason might be?

Thanks!

2 Answers 2

3

They both generate completely identical Uri objects, except (obviously) for the OriginalString.

You can see this in LINQPad:

var filePath = @"C:\temp\tmp1234.tmp";    // Generally obtained from System.IO.* calls
new []{ 
    new Uri("file://" + filePath),
    new Uri(filePath)
}.Dump();

I would guess that the original developer wasn't aware of that.

1
  • Nifty tool. Playing around with it I see that there is a difference if filePath = @"C:\temp\temp12%34.tmp"! using "file://" seems to assume it's already been URL-encoded so the LocalPath comes out munged (or at least not what was put in: C:\temp\temp124.tmp).
    – Russ
    Aug 29, 2011 at 20:01
1

Actually, adding "file://" forces the scheme, and therefore skips the need for .NET to call the "ParseSchemeCheckImplicitFile" method... so... it's [negligibly] faster.

That, and, it's explicit - which I prefer personally.

EDIT: Actually, what I should have said is it skips a lot of code in that method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.