aherlambang
aherlambang

Reputation: 14418

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);

Upvotes: 9

Views: 20190

Answers (3)

vibs2006
vibs2006

Reputation: 6528

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");
            }

Upvotes: 1

driis
driis

Reputation: 164291

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.

Upvotes: 24

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

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?

Upvotes: 8

Related Questions