Sunday, July 10, 2011

How to access files, folders and other local resources through .net

Applications these days may require to access local resources such as folders on disk, creating/deleting files, etc. I came across one such scenario wherein the application had to create a file on remote location and then periodically delete the file(2 days after file creation).

In this scenario, assume without the application in picture, an user creates a file. This seems pretty much simple though, but what I want to tell here is the sequence of events.

1. An user navigates to the location ( a folder on remote machine)
2. Create a file
3. Save the file.

These 3 events though straightforward, make an important assumption, and that is, the user is having access to create file.

When it comes to your .Net application, the application is running under the user of a lesser privilege (that's CAS for you) or Code Access Security. So most of the times it won't have the privilege to create a file.

To fix this either you have to grant the application account with the required privilege OR you can MAKE the application run on the privilege of a specific user.

So under which username does the .Net app really work ??-- Its Network Service for remote apps and ASPNET on local machines.

As discussed you can grant these users, depending on the scenario, access to the required folders and you're done. But theres a trap... All the .Net apps will now have access to this folder since all of them run by Network Service/ASPNET accounts.

It may happen that you have to restrict the access to such folders, then, you have only one option...execute the application under the context of a specific user who has access to only that location. To get this done, you need to explore WindowsImpersonation class. Below is the link with code sample

WindowsImpersonation class

With this class you can provide the username/password of the specific user account you want the application to execute and then reset the identity so that the rest of the application code works under the restricted .Net account.

Happy Coding :)

No comments: