1

I am using ASP.NET for my web application. I am able to write a text file in server path using this method Server.MapPath(). But I also want to create a text file in different location like C:\ or D:\. I am using IIS version 5.1.

This is my code to write a file in the C:\ drive.

    string text="Welcome";
    StreamWriter sw = new StreamWriter("C:\\sample.txt", true);
    sw.WriteLine(text);
    sw.Close();

When I run the application it throws a runtime exception saying

UnauthorizedAccessException. Access to Path C:\sample.txt is denied.

Please guide me how to write a text file in the C:\ drive...

4 Answers 4

3

Its obvious that you need permission to be able to create/write/delete etc a file on any location on disk.

The tip here is that your asp.net application is running under one pool, and the pool is running under specific user - this user must have the correct permissions.

Update

There is two kind of users that "runs" together on an asp.net page. The one have to do with permission with IIS, and this is the one that KBoek speak about. For example, a user request a page , from IIS, and the IIS using the USER A to see if can read this file and send it back to web - or have permissions to run.

The second type of user is the pool. From the moment that IIS have permissions to run the pool then run it using the pool user. So if the file is going to read by pool the pool must have permission to read and not the iis.

Why there are two kind of users here. Because the one is represent the user that see the data, and the other represent the programming that we made.

If for example we have an automation tool that make delete to a set of files, then we do not won to the remote client to direct access this file and maybe delete if he like to - but only we must have this permission to do only on programming. So our asp.net program have different permissions from the user that connect and see page, so we have two kind of users here.

2

The server process runs under a specific user (dependent on your IIS version), that user has to have write access to the folder where you want to save the file. Tell me your IIS version, then give me a minute and I'll look up the user name for you.

3
1

In order to write into a certain location, the web server user must have write access granted to that location. You have to set up the folder rights to this for work. The exact user depends on your IIS version.

0

First of all I'd use Server.Mappath("C:\\sample.txt");.

Secondly, the exception says it all, the user attempting to write a file in the server does not have the permission to write.

Check Checking and Setting up the Correct Permissions on the IIS Server for permissions

Find your user and allow it to write.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.