Uri constructor throws exception for relative path without UriKind - c#

Why is
new Uri("temp/file.txt")
throwing the following exception
UriFormatException: Invalid URI: The format of the URI could not be determined.
instead of creating a relative Uri? It doesn't know the format so why do I need to specify the UriKind.Relative argument? It still doesn't know the format when I do it. This is counterintuitive.
Is there a way to create a relative Uri without having to use the UriKind argument? Having to do this untermines the purpose of the Uri class because I now cannot use it for implicit string --> Uri converstion without checking the string myself each time.

You may want to create it by specifying RelativeOrAbsolute as UriKind:
var uri = new Uri("temp/file.txt", UriKind.RelativeOrAbsolute);

Related

Characters after "#" is not recognized by system.net.webclient.DownloadFile method [duplicate]

How do you properly encode a path that includes a hash (#) in it? Note the hash is not the fragment (bookmark?) indicator but part of the path name.
For example, if there is a path like this:
http://www.contoso.com/code/c#/somecode.cs
It causes problems when you for example try do this:
Uri myUri = new Uri("http://www.contoso.com/code/c#/somecode.cs");
It would seem that it interprets the hash as the fragment indicator.
It feels wrong to manually replace # with %23. Are there other characters that should be replaced?
There are some escaping methods in Uri and HttpUtility but none seem to do the trick.
There are a few characters you are not supposed to use. You can try to work your way through this very dry documentation, or refer to this handy URL summary on Stack Overflow.
If you check out this very website, you'll see that their C# questions are encoded %23.
Stack Overflow C# Questions
You can do this using either (for ASP.NET):
string.Format("http://www.contoso.com/code/{0}/somecode.cs",
Server.UrlEncode("c#")
);
Or for class libraries / desktop:
string.Format("http://www.contoso.com/code/{0}/somecode.cs",
HttpUtility.UrlEncode("c#")
);
Did some more digging friends and found a duplicate question for Java:
HTTP URL Address Encoding in Java
However, the .Net Uri class does not offer the constructor we need, but the UriBuilder does.
So, in order to construct a proper URI where the path contains illegal characters, do this:
// Build Uri by explicitly specifying the constituent parts. This way, the hash is not confused with fragment identifier
UriBuilder uriBuilder = new UriBuilder("http", "www.contoso.com", 80, "/code/c#/somecode.cs");
Debug.WriteLine(uriBuilder.Uri);
// This outputs: http://www.contoso.com/code/c%23/somecode.cs
Notice how it does not unnecessarily escape parts of the URI that does not need escaping (like the :// part) which is the case with HttpUtility.UrlEncode. It would seem that the purpose of this class is actually to encode the querystring/fragment part of the URL - not the scheme or hostname.
Use UrlEncode: System.Web.HttpUtility.UrlEncode(string)
class Program
{
static void Main(string[] args)
{
string url = "http://www.contoso.com/code/c#/somecode.cs";
string enc = HttpUtility.UrlEncode(url);
Console.WriteLine("Original: {0} ... Encoded {1}", url, enc);
Console.ReadLine();
}
}

.NET Uri: unexpected Uri using constructor to combine paths

I'm using constructor:
public Uri(Uri baseUri, string relativeUri)
to append relative paths to an initial Uri.
Usually, everything works OK and the desired path is appended, but, in some cases, the final path is REPLACED.
For example, with this code:
new Uri(new Uri("http://localhost:3000/app/api/publicapi/NAS_0x5d65d971895edc438f465c17db6992698a52318d"), "Blocks")
I expected this result:
http://localhost:3000/app/api/publicapi/NAS_0x5d65d971895edc438f465c17db6992698a52318d/Blocks
But I get:
http://192.168.26.50:3000/app/api/publicapi/Blocks
What's wrong, here?
Missing the final slash so it's treating NAS_0x5d65d971895edc438f465c17db6992698a52318d as a resource not a path:
var existingUri =
new Uri("http://localhost:3000/app/api/publicapi/NAS_0x5d65d971895edc438f465c17db6992698a52318d/");
new Uri(existingUri, "Blocks");
// returns: http://localhost:3000/app/api/publicapi/NAS_0x5d65d971895edc438f465c17db6992698a52318d/Blocks
From docs:
If the baseUri has relative parts (like /api), then the relative part
must be terminated with a slash, (like /api/), if the relative part of
baseUri is to be preserved in the constructed Uri.

Is there a workaround to create a URI with an underscore in .NET?

I'm trying to create a URI which contains an underscore (it's pointing to a UNC path) like so:
hplLink.NavigateUri = new Uri(String.Format("{0}\\{1}", selectedFolder.LinkTitle, selectedFolder.FolderPath), false);
Unfortuantely this chokes up with the following:
Invalid URI: The format of the URI could not be determined.
I need to essentially create a hyperlink in a WPF application and I am unable to do so on paths containing an underscore.
Any thoughts would be greatly appreciated.
Thanks!

How to convert Image URL to ImageStream ?

I was doing this for local image
var imgstream = System.IO.File.OpenRead(#"C:\Users\TheSarfaraz\Downloads\SampleFacebookApp\SampleFacebookApp\SampleFacebookApp\Content\images\dreams-facebook-cover_4173.jpg");
But its not letting me do this for image URL
If I try this
var imgstream = System.IO.File.OpenRead(#"http://www.trendycovers.com/covers/Listen_to_your_heart_facebook_cover_1330517429.jpg?i");
I'm getting this error
URI formats are not supported.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: URI formats are not supported.
You can't ask for a web resource, such as image, to be treated as a regular file and to use I/O operations, such as FileStream, on it.
In your case, you should use the WebClient class which is using the HTTP GET method in order to download the image properly.
For example:
using (WebClient Client = new WebClient ())
{
Client.DownloadFile(#"http://www.trendycovers.com/covers/Listen_to_your_heart_facebook_cover_1330517429.jpg?i", "Listen_to_your_heart_facebook_cover_1330517429.jpg");
}
The image file will be downloaded to your application folder unless you declare absolute path in the second parameter (fileName), such as: c:\images\Listen_to_your_heart_facebook_cover_1330517429.jpg
You are using the wrong class. You can not read a file from a webserver with the File.OpenRead function because this is not designed for that purpose. Try the WebClient.OpenRead function instead.

Using System.Uri to remove redundant slash

I have a condition in my program where I have to combine a server (e.g. http://server1.my.corp/) that may or may not have an ending slash with a relative path (e.g. /Apps/TestOne/). According to the docs, Uri should...
Canonicalizes the path for hierarchical URIs by compacting sequences such as /./, /../, //,...
So when I do something like var url = new Uri(server + relativePath), I'd expect it to take what would otherwise be http://server1.my.corp//Apps/TestOne/ and remove the double slash (i.e // -> /), but ToString, AbsolutePath and various options still show the redundant/duplicate slash. Am I not using Uri right?
Take a look at the constructors for the Uri class. You need to specify a base Uri and a relative path to get the canonized behavior. Try something like this:
var server = new Uri("http://server1.my.corp/");
var resource = new Uri(server, "/Apps/TestOne/");

Categories

Resources