1

In My WPF App i have some pages, and I need to check for example:

new Uri("Pages/Page2.xaml", UriKind.Relative)

exist or not, I tried somethig semilar to this, just from Absolute replaced to Relative

 bool IsRelativeUrl(string url)
 {
    Uri result;
    return Uri.TryCreate(url, UriKind.Relative, out result);
 } 

Then Is printed:

string url = "Pages/Page2.xaml";
MessageBox.Show(IsRelativeUrl(url).ToString());  

And it says always true, even for non existing pages

BugsFixer
  • 377
  • 2
  • 15

1 Answers1

1

You can't use an Uri to determine whether a resource exists. You need to look for the compiled BAML resource:

bool IsRelativeUrl(string url)
{
    Assembly assembly = Assembly.GetExecutingAssembly();
    string[] resources = assembly.GetManifestResourceNames();

    //Stream bamlStream = null;
    foreach (string resourceName in resources)
    {
        ManifestResourceInfo info = assembly.GetManifestResourceInfo(resourceName);
        if (info.ResourceLocation != ResourceLocation.ContainedInAnotherAssembly)
        {
            using (Stream resourceStream = assembly.GetManifestResourceStream(resourceName))
            using (ResourceReader reader = new ResourceReader(resourceStream))
            {
                foreach (DictionaryEntry entry in reader)
                {
                    if (entry.Key.ToString().Equals(url.ToLower()))
                        return true;
                }
            }
        }
    }
    return false;
}

Usage:

string url = "Pages/Page2.baml"; //<-- note the file extension
MessageBox.Show(IsRelativeUrl(url).ToString());  
mm8
  • 163,881
  • 10
  • 57
  • 88