I’ve been writing a component that streams a file to the user based up a supplied path. The path can either be a Uniform Resource Idendfier (URI) or a standard Windows path, e.g. C:\My Documents\MyDoc.doc
The problem is that the majority of the streaming enabled .net components accept either a URI or a file path but not both. Therefore my code has to understand if the passed in string contains a URI or a file path. My first port of call was Uri.IsWellFormedUriString which returns true if the string contains a URI. So if it’s a valid URI then I use the URI Streaming components otherwise I’ll use the FileStream components…however, what if they’ve supplied a URI but have simply messed up the encoded, this would fail and then attempt to supply a dodgy URI to the file streaming code. I thought I was going to have do some exception catching (yuk) but to my suprise File.Exists doesn’t seem to care about the format of the file path, either it can see it or it can’t, regardless of what rubbish you enter. So I can happily assume a file path for any invalid URI and providing I check that the file exists I don’t have to do any nasty exception handling
I also encountered some slightly quirky behaviour to URI.TryCreate that creates a URI or fails without raising an exception. I started to use this but discovered that it always seemed to successfully create a URI (using the file:// schema) no matter what invalid text I threw at it. So be careful when using that method.