Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing data to App_Data

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);
like image 469
aherlambang Avatar asked Apr 04 '10 13:04

aherlambang


3 Answers

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.

like image 112
driis Avatar answered Nov 11 '22 04:11

driis


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?

like image 8
Matti Virkkunen Avatar answered Nov 11 '22 02:11

Matti Virkkunen


Above Answers are good, however they are dependent on System.Web assembly.

If you are creating File Creation method inside a library then Server.MapPath won't be available there.

In that case you can use even a more universal say to write the data in App_Data folder.

We use App_data folder because a hacker cannot access files in app_data folder with http/https urls (e.g http://yourwebsite.com/app_data/test.xml

            var rootDirectory = AppDomain.CurrentDomain.BaseDirectory;
            var folderNameToBecreated = "posts"; //
            var finalDirectoryPath = System.IO.Path.Combine(rootDirectory, "App_Data", folderNameToBecreated);
            var filename = Guid.NewGuid().ToString() + ".txt";

            //Create Directory if not exists
            if (System.IO.Directory.Exists(finalDirectoryPath) == false)
            {
                System.IO.Directory.CreateDirectory(finalDirectoryPath);
            }

            var fullFilePath = System.IO.Path.Combine(finalDirectoryPath, filename);
            //testing your written file
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fullFilePath, true))
            {
                sw.WriteLine("This is a test file");
            }
like image 1
vibs2006 Avatar answered Nov 11 '22 04:11

vibs2006