C # Uri loading not deterministic?

I am trying to download some BitmapImages files from files stored in the file system. I have a dictionary of keys and relative file paths. Unfortunately, the Uri constructor seems non-deterministic in how it will load images.

Here is my code:

foreach(KeyValuePair<string, string> imageLocation in _imageLocations) { try { BitmapImage img = new BitmapImage(); img.BeginInit(); img.UriSource = new Uri(@imageLocation.Value, UriKind.Relative); img.EndInit(); _images.Add(imageLocation.Key, img); } catch (Exception ex) { logger.Error("Error attempting to load image", ex); } } 

Unfortunately, sometimes Uris loads as a relative Uris file, and sometimes they load as a relative Uris Pack. There seems to be no rhyme or reason why it will load that way. Sometimes I get the entire Uris download in one direction, or just a couple or most of them, and every time I run the code, it will change.

Any ideas on what's going on here?

+6
source share
2 answers

Well, sort of ... MSDN has this to say about UriKind:

Absolute URIs are characterized by a full reference to the resource (example: http://www.contoso.com/index.html ), while the relative URI depends on the previously defined base URI (example: /index.html)

If you jump into the reflector and look around, you can see that there are many ways for the code to be taken to decide what the relative URI should. In any case, this is not that it is not deterministic, especially since it is simply the main source of disappointment for many developers. One thing you can do is use the BaseUriHelper class to understand how your problems are resolved.

On the other hand, if you know where your resources are stored (and you should), I suggest you just get rid of the headache and use an absolute URI to solve your resources. It works every time, and there is no dumb code behind the scenes to distract you when you least expect it.

+3
source

In the end, I solved the problem by getting the base directory of my application and adding a relative path to it and using an absolute URI, not a relative.

 string baseDir = AppDomain.CurrentDomain.BaseDirectory; foreach(KeyValuePair<string, string> imageLocation in _imageLocations) { try { BitmapImage img = new BitmapImage(); img.BeginInit(); img.UriSource = new Uri("file:///" + baseDir + @imageLocation.Value, UriKind.Absolute); img.EndInit(); _images.Add(imageLocation.Key, img); } catch (Exception ex) { logger.Error("Error attempting to load image", ex); } } 
+1
source

Source: https://habr.com/ru/post/886196/


All Articles