在我的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());
它说总是正确的,即使对于不存在的页面
答案 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());