Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory.Exists not working for a network path

I have a line of code checking if a directory exists and then getting the list of files in it.

System.IO.Directory.Exists(@"\\Server\Folder\");

I works when I test it (run from visual studio), but when I deploy the web site, it always returns false.

I do the same verification for another folder, on another server (let's say Server2) and it works fine.

I then thought it was an access issue, but the shared folder and network have all access to everyone... Is there another reason why it would not work?

like image 501
Amaranth Avatar asked Apr 17 '12 18:04

Amaranth


3 Answers

When you run the code in Visual Studio it runs under the the rights of your user.

When you run the code in IIS it runs in the identity of the Application Pool which by default is the built in user "Network Service" this is a local user account which does not have access outside the local machine.

The rights on the network share are the first layer, after that the NTFS rights on the directory are checked.

You need to change the identity of the application pool to a domain user with the same rights as your user.

like image 122
Shiraz Bhaiji Avatar answered Oct 16 '22 17:10

Shiraz Bhaiji


I may be a little late, but i've found that there is a problem on this method of the Directory class. Instead i've used DirectoryInfo with impersonation this way:

new DirectoryInfo(path).Exists

This way you avoid the whole identity change problem, which was denied by our IT area.

I hope this helps somebody!

like image 29
Gonza Oviedo Avatar answered Oct 16 '22 18:10

Gonza Oviedo


For future references, this also works:

bool result = false;
try
{
    Directory.GetAccessControl(path);
    result = true;
}
catch (UnauthorizedAccessException)
{
    result = true;
}
catch
{
    result = false;
}
like image 30
Mirko Bellabarba Avatar answered Oct 16 '22 18:10

Mirko Bellabarba