【问题标题】:XDocument.load(string uri) throws ArgumentNullExceptionXDocument.load(string uri) 抛出 ArgumentNullException
【发布时间】:2023-04-02 12:22:01
【问题描述】:

我在调用时收到 ArgumentNullException

string filepath = @"AppData\TestAppData.xml";
        if (filepath != null)
        {
            XDocument xdoc = XDocument.Load(filepath); 
        }

以下是异常详情。它说,“格式”参数为空 - 但在什么时候我可以控制这个参数? 或者我的错误到底是什么?

> System.ArgumentNullException was unhandled by user code
>     HResult=-2147467261
>     Message=Value cannot be null.
>     Parameter name: format
>     ParamName=format
>     Source=mscorlib
>     StackTrace:
>        at System.String.FormatHelper(IFormatProvider provider, String format,   ParamsArray args)
>        at System.String.Format(String format, Object[] args)
>        at System.SR.Format(String resourceFormat, Object[] args)
>        at System.Xml.XmlException.CreateMessage(String res, String[] args, Int32 lineNumber, Int32 linePosition)
>        at System.Xml.XmlException..ctor(String res, String[] args, Exception innerException, Int32 lineNumber, Int32 linePosition, String
> sourceUri)
>        at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
>        at System.Xml.XmlTextReaderImpl.ParseAttributeValueSlow(Int32 curPos, Char quoteChar, NodeData attr)
>        at System.Xml.XmlTextReaderImpl.ParseAttributes()
>        at System.Xml.XmlTextReaderImpl.ParseElement()
>        at System.Xml.XmlTextReaderImpl.ParseElementContent()
>        at System.Xml.XmlTextReaderImpl.Read()
>        at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r)
>        at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r, LoadOptions o)
>        at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
>        at System.Xml.Linq.XDocument.Load(String uri, LoadOptions options)
>        at System.Xml.Linq.XDocument.Load(String uri)

【问题讨论】:

  • 看起来像无效的 XML。
  • 但是,它不应该从该级别的代码中抛出空引用异常......
  • 同意,看起来像一个严重到足以使解析器在生成一个体面的报告之前触发的 XML 错误。
  • @redGreen - 尝试在 Visual Studio 或其他编辑器中打开 XML 文件。看看你是否可以通过这种方式获得错误报告。
  • 是的。谢谢!解决了它:) 缺少一个结束标签..

标签: c# linq-to-xml argumentnullexception system.xml


【解决方案1】:

你需要这个

string EnviromentPath = Path.GetDirectoryName(HostingEnvironment.ApplicationPhysicalPath);

获取项目目录的路径 然后你应该在那之后将它们组合起来

Path.Combine(EnviromentPath,@"AppData\TestAppData.xml");

【讨论】:

  • 不,错误的路径不会导致 NullRef 异常。
【解决方案2】:

看看这个:How I use XDocument.Load() to get a file in the application directory

文件路径好像不对,试试这个

XDocument xdoc = XDocument.Load(filepath); 

【讨论】:

  • 丢失或无法打开的文件会产生不同的异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多