Writing data to App_Data

有些话、适合烂在心里 提交于 2020-01-02 02:20:08

问题


I want to write a .xml file using the following code into the App_Data/posts. Why is it causing an error?

Code

 Stream writer  = new FileStream("..'\'App_Data'\'posts'\'" + new Guid(post_ID.ToString()).ToString() + ".xml", FileMode.Create);

回答1:


Please post the exception you are getting; not just "it does not work" - this can be all sorts of problems. Here is a few things to check:

Check whether the ASP.NET process has write access to that directory.

Also, it looks like you are escaping the backspaces in the path wrong. And when working with ASP.NET, your paths should be relative to the application root directory. Try this:

string path = HttpContext.Current.Server.MapPath("~/App_Data/posts/" + new Guid(post_ID.ToString()).ToString() + ".xml"
Stream writer  = new FileStream(path, FileMode.Create);

Finally, ensure that the posts directory exists - or the file creation will fail.




回答2:


Remove the extraneous single quotes and escape your backslashes properly.

Or even better, use Server.MapPath (available in the Page and UserControl base classes and the HttpContext among other things).

Server.MapPath("~/App_Data/posts/" + new Guid(post_ID.ToString()).ToString() + ".xml")

Out of curiosity, what is the type of post_ID? Why are you converting it into a string, then into a guid, and then back to a string?



来源:https://stackoverflow.com/questions/2574587/writing-data-to-app-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!