简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM