Hoody
Hoody

Reputation: 3381

Getting path of file

I am using the C# code below to get the url to an xml file. The current page is News.aspx and the XML file is in the same folder, which is why this works fine.

xUrl = Request.Url.GetLeftPart(UriPartial.Path).Replace("News.aspx", "news.xml");

But it feels a little wrong to me, what if News.aspx changed? Is this the right way to do this sort of thing? Or is there a better way to get the URL of a file?

Thanks

Upvotes: 0

Views: 129

Answers (2)

Matt
Matt

Reputation: 3812

I would use Server.MapPath to get the URL of a file.

 private string GetPathOfMyXMLFile(string name){
     return Server.MapPath("~/Resources/"+name+".xml");
 }

you can then get this in your code

 // Bla bla load file
 string path = GetPathOfMyXMLFile("News");

You could add www.donetnukelabs' suggested answer and pop the name of your xml file into a settings store (web config perhaps), if it's likely to change.

Upvotes: 1

Prashant Lakhlani
Prashant Lakhlani

Reputation: 5806

There are many ways you can resolve this, you can introduce constant in the system, or you can use appSettings in web.config to store relative path to the folder for news.xml.

You are right, your current method is not considered good practice.

Upvotes: 1

Related Questions