Thursday, March 31, 2011

Calling Directory.Exists("\\SERVER\SHARE\") in Setup Project

I have a .NET Setup Project to which I've added a custom installer action. During the setup process, the user has to provide a path (which often is a UNC path) to a share on their file server. I attempt to do some validation before proceeding to make sure the directory exists, as such:

if (!Directory.Exists(serverDirectory)) { 
    throw new InstallException("Specified path does not exist or ..."); 
}

Pretty vanilla -- and in a console app, the Directory.Exists() code works as expected. However, in the context of the MSI, it does not. Specifically, the call to Directory.Exists always fails when using a network resource. The documentation for Directory.Exists does indicate why:

The Exists method does not perform network authentication. If you query an existing network share without being pre-authenticated, the Exists method will return false.

Searches have led me to other similar scenarios in ASP.NET where impersonation is the solution. That isn't applicable here, but it illustrates the issue.

How can I check for the existence of the network path? To put in the language of the documentation -- how do I pre-authenticate before the call? The user is installing as an administrator, and browsing to that path in Windows Explorer works successfully, so it's not permissions of the user, but rather a lack of checking by the code.

Have I created an unnecessary concern -- should I omit this and throw the exception later when trying to use the network resource... it's largely the same critical failure, right?

From stackoverflow
  • It's not just existence: you need to check for permissions as well, and worry about what happens if they change on you in the period between when you check and when you actually use the value.

    Therefore the normal mechanism is to just assume everything is okay. Instead, put your development effort into handling the exception when the assumption proves false, because you need to be able to do that gracefully anyway.

    For this case, you might be able to improve on that by immediately creating a small placeholder file in directory in question, and holding a lock on that file until you're completely finished with the folder. That would allow you to give some better feedback, since you'll get an immediate error trying to create the file. It also helps guarantee that the folder stays accessible, since under windows at least users will have a hard time deleting or significantly changing folder as long as you hold a lock to that file.

0 comments:

Post a Comment