How to ensure network drives are connected for an application?

CJ7 picture CJ7 · Jan 16, 2012 · Viewed 14.4k times · Source

I have a desktop Windows application that is installed in small office environments.

The application uses an .MDB database file as its database which is stored on a network drive.

Configuration files specify the path of the .MDB file on the server using a letter drive: eg. f:\data\db.mdb

The application needs to access this database file when it starts. How can I ensure the network drive is connected and accessible when the application starts?

Sometimes Windows doesn't reconnect network drives and the only way to connect them is to double-click on them in My Computer, even when "Reconnect at logon" is ticked when mapping the drive.

Would a solution be to use \\machine_name\share instead of drive letters?

Answer

JimmyPena picture JimmyPena · Jan 24, 2012

You should use UNC paths, because not everyone will have your drive mapped to the same letter.

Determine UNC path

First, I would determine the UNC path of your file as it exists on your local computer at F:\data\db.mdb using one of the techniques found here:

Basically, you look at the way Windows Explorer lists the network mapped drive, then use this to deduce the UNC path.

Check Availability using WMI

Assuming the drive is actually mapped on every local computer that plans to use the application, use the Win32_MappedLogicalDisk class to determine availability of the mapped network drive.

I have some sample code here that can be adapted to determine whether a given network drive is available (scroll down to the Mapped Drives Information section). You check .ProviderName to match the UNC path, so you know which is the correct drive, then check the value of .Availability to determine if the mapped network drive can be accessed.