【问题标题】:WPF C# How to check URI file existsWPF C#如何检查URI文件是否存在
【发布时间】:2019-03-16 06:32:22
【问题描述】:

我正在使用这样的代码。 当 lan 为空时,我收到异常 TypeInitializationException.

有什么方法可以检查 URI 是否为空?

ResourceDictionary dict = new ResourceDictionary();

dict.Source = new Uri("/Emdep.Geos.UI.Common;component/Resources/Language." + lan + ".xaml", UriKind.RelativeOrAbsolute);

    An unhandled exception of type 'System.TypeInitializationException' occurred in Emdep.Geos.UI.Common.dll## Heading ##

【问题讨论】:

  • 我不确定,但在我看来,当你做你描述的事情时得到例外是好的。 lan 不应为空。它应该使用您的应用支持的默认语言进行初始化。检查您的嵌入式资源中是否有语言会很奇怪。
  • 我的意思是,lan 是计算机中不存在的任何文件名/空值然后抛出异常
  • 如果lannull,你想做什么?
  • @SagarKhade 所以我理解正确,它不仅会在lannull 时抛出这个异常,而且当文件路径不存在时也会抛出这个异常?
  • 是的,你是对的

标签: c# wpf


【解决方案1】:

你应该做的是捕捉FileNotFoundException找不到时发生的ResourceDictionary

ResourceDictionary dict = new ResourceDictionary();
try
{
    dict.Source = new Uri("/Emdep.Geos.UI.Common;component/Resources/Language." + lan + ".xaml", UriKind.RelativeOrAbsolute);
}
catch (FileNotFoundException)
{
    //the resource dictionary could not be located/loaded...
}

【讨论】:

  • 这是一个抛出的 IOException 而不是 FileNotFoundException
  • @kjhf:不,不是。
  • 好吧,又挖了一些,我遇到的异常是“无法找到资源'(uri)'”,我认为它是文件未找到并输入为 IOException。然而,异常的真正原因是没有找到程序集而不是文件。按原样使用您的代码会产生 IOException,因为我的程序集不知道 Emdep.Geos.UI.Common
猜你喜欢
  • 2017-04-24
  • 1970-01-01
  • 2016-02-23
  • 2019-07-11
  • 2011-11-01
  • 1970-01-01
相关资源
最近更新 更多