检查是否存在相对Uri

时间:2019-02-17 14:17:52

标签: wpf xaml uri

在我的WPF应用中,我有一些页面,例如,我需要检查:

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

存在与否,我尝试将this改成AbsoluteRelative

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

然后打印:

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

它说总是正确的,即使对于不存在的页面

1 个答案:

答案 0 :(得分:1)

您不能使用Uri来确定资源是否存在。您需要查找已编译的 B AML资源:

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;
}

用法:

string url = "Pages/Page2.baml"; //<-- note the file extension
MessageBox.Show(IsRelativeUrl(url).ToString());