Neo
Neo

Reputation: 16219

How to read xml file in .net windows application in different directory?

I have one .net windows application I'm trying to read .xml file from c# windows application.

but i'm getting error :

Could not find a part of the path 'c:\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\~\Files\test.xml'.

but my file is in Files folder which is in application WindowsFormsApplication1 only not in \bin\Debug

then why it is searching into \bin\Debug ?

code in form.cs

DataSet dsAuthors = new DataSet("authors");
            string filePath = @"~/Files/test.xml";

            dsAuthors.ReadXml(filePath);

also please tell me is there any way to use Server.MapPath like we do it in web application.

I tried other solution like :

string appPath = Path.GetDirectoryName(Application.ExecutablePath);

            System.IO.DirectoryInfo directoryInfo = System.IO.Directory.GetParent(appPath);
            System.IO.DirectoryInfo directoryInfo2 = System.IO.Directory.GetParent(directoryInfo.FullName);

            string path = directoryInfo2.FullName + @"\Files";

but getting error : Access to the path is denied.

Upvotes: 1

Views: 3001

Answers (2)

Ivan Golović
Ivan Golović

Reputation: 8832

Try:

        string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine("Files", "test.xml"));// @"~/Files/test.xml";

If it doesn't work make sure that the test.xml has "Copy to output directory" property set to "Copy always".

Upvotes: 2

nunespascal
nunespascal

Reputation: 17724

Use Server.MapPath

You are using a relative url. This will not work with ReadXml. It needs the absolute path on your disk.

Server.MapPath will take your virtual path and give you its absolute path.

var fullPath = Server.MapPath("~/Files/test.xml");
dsAuthors.ReadXml(fullPath);

Note: Server.MapPath doesn't verify if the path actually exists.

Upvotes: 0

Related Questions