XDocument.load(string uri)抛出ArgumentNullException

时间:2015-06-08 12:20:00

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

调用

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

以下是例外细节。它说,"格式"参数为null - 但是在哪个时候我可以控制这个参数? 或者我的错误究竟是什么?

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

2 个答案:

答案 0 :(得分:0)

你需要这个

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

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

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

答案 1 :(得分:0)

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

似乎文件路径不正确,试试这个

XDocument xdoc = XDocument.Load(filepath);