【问题标题】:Check if relative Uri exist检查是否存在相对 Uri
【发布时间】:2019-07-11 01:28:27
【问题描述】:

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

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

存在与否,我尝试了一些与this 相似的东西,只是从Absolute 替换为Relative

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

然后被打印出来:

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

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

【问题讨论】:

  • 有效的 URI 并不意味着引用的资源存在或可用。

标签: wpf xaml uri


【解决方案1】:

您不能使用Uri 来确定资源是否存在。你需要寻找编译好的BAML资源:

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());  

【讨论】:

    猜你喜欢
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 2019-03-16
    • 2012-07-27
    • 2018-02-11
    • 2015-01-19
    • 2013-05-12
    相关资源
    最近更新 更多