XDocument.load(string uri) throws ArgumentNullException

980 views Asked by At

I get an ArgumentNullException when calling

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

Here are the exception details. It says, that the "format" parameter is null - but at which point am I able to control this parameter? Or what exactly is my mistake?

> 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

There are 2 answers

1
Stoyan Uzunov On

You need this

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

to get the path to your project directory and then you should combine them after that

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

Have a look at this: How I use XDocument.Load() to get a file in the application directory

It seems the filepath is not correct, try this

XDocument xdoc = XDocument.Load(filepath);