Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory.exists returns false for mapped drive in c# coding

Tags:

c#

directory

I am using Directory.Exists() in my windows service (that is programmed in C#, 3.5 framework)to check to see whether a particular directory exists in the drive. When I run in local machine it works fine, meaning I am able to access the directory.

But when I deploy the windows service on a Virtual Machine, and start the service, it is not able to find the directory even though the directory exists. The directory is mapped on as

 Q: drive, Q:\\temp\\local\\ folder 

But the windows services always returns false for the Directory.Exists().

However when I give C:\ drive in place of Q:\ it works, but does not work for a mapped drive. I have tried with the UNC path, and I have made sure the mapped drive have the administrative rights and infact the read, write and execute permission. But it still returns false.

Can anyone please tell me why? And how to resolve?

like image 443
user2749638 Avatar asked Sep 05 '13 09:09

user2749638


4 Answers

Make sure the drive is mapped under the same user as the Service is running. If you map the drive as user A, it is not automatically mapped for anyone else too.

like image 86
user2674389 Avatar answered Nov 15 '22 06:11

user2674389


Mapped drives are only restored during interactive login which services generally do not perform:

Map a network drive to be used by a service

Short version: You can't do it, use the full UNC path instead.

like image 34
Ashigore Avatar answered Nov 15 '22 07:11

Ashigore


This is most probably a problem with privileges. Your Windows service is probably running under an account which doesn´t have enough privileges to access the network path.

This is a possible duplicate: Accessing mapped folder from a Windows Service written in C#

Another possible solution is to use impersonation, check it out: http://msdn.microsoft.com/en-us/library/w070t6ka(v=vs.90).aspx

UPDATE

Came to think of it; Try changing the identity of the application pool to a user with the same rights as your user.

like image 40
Marcus Avatar answered Nov 15 '22 07:11

Marcus


As @Sriram pointed out the Directory.Exists() method will fail if any error occurs. What sort of exception do you get if you try to access the path?

Eg (for both mapped and UNC in case there is something going on there):

DirectoryInfo diMapped = new DirectoryInfo(@"Q:\temp\local\folder");
DirectoryInfo diUNC = new DirectoryInfo(@"\\servername\fnsw\tmp\126");

Note: Assuming that the white space before 'folder' in your path is a typo?

like image 29
Kyle Avatar answered Nov 15 '22 06:11

Kyle