mucchar
mucchar

Reputation: 111

relative path using c#

I am using c#. In my project I am having a xml folder in which i have an xml file say "file.xml".. I want to use the file in my project. I want to take that file from the current project itself,for that I am giving the path as:

  xmlDoc.Load(@"..\xml\file.xml");

but it is not taking the file. It is showing some "C:" path.. how can I retrive this file from project itself.

Upvotes: 6

Views: 24373

Answers (3)

SLaks
SLaks

Reputation: 888157

You should set the Copy to Output Directory property on the file in the Solution Explorer to gocpy the file to the folder with your EXE.

You can then write

xmlDoc.Load(Path.Combine(typeof(MyClass).Assembly, "file.xml"));

This uses the actual location of the EXE file and will work regardless of the current directory.

EDIT: In ASP.Net, you should put your file in the App_Data folder (which is not publicly accessible), then write

xmlDoc.Load(Server.MapPath("~/App_Data/file.xml"));

Upvotes: 6

Kishore Borra
Kishore Borra

Reputation: 269

Path.Combine(typeof(MyClass).Assembly.Location.ToString(), "file.xml")

Upvotes: 0

jaywayco
jaywayco

Reputation: 6296

You should set the Copy to Output Directory to "copy if newer" and you can then use:

Path.Combine(Application.StartupPath, "file.xml");

Upvotes: 2

Related Questions