How do you access the "remembered" location of a Windows network drive via Python?

Question:

I’m using the pywin32 Windows API library to pull information about network drives using the win32wnet.WNetGetConnection() function. When I perform this function on network drives Windows reports as "Unavailable" (Status), the function returns a win32wnet.error stating "The device is not currently connected but it is a remembered connection." How can I get access to that "remembered" path data that this function is not returning to me?

So far, I’ve done some error handling on the function to find out more information about what type of error is being returned, but that hasn’t brought me any closer to actually accessing the remembered path data as it is being thrown away by the function instead of returned.

I’ve tried some workarounds with the subprocess module, using the Windows console "net use" command, but the solution is not particularly elegant and I will only use it as a last resort.

Here is an explicit example of the code:

for letter in ascii_lowercase:
    try:
        drive_path = win32wnet.WNetGetConnection(letter + ":")
    except win32wnet.error as exception:
        print(exception)

Here is an exception that is being returned by the win32wnet.WNetGetConnection() function:

(1201, 'WNetGetConnection', 'The device is not currently connected but it is a remembered connection.')
Asked By: dustmole

||

Answers:

I found a solution to this. Network drive paths are remembered because they are stored in the registry. I imported the standard library module "winreg" for accessing the paths and modified my code as such:

#Retrieve a remembered network connection from the Windows user registry
def getRememberedConnection(drive_letter):
    registryConnection = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
    if registryConnection:
        registryKey = winreg.OpenKey(registryConnection, rf'Network{drive_letter}')
        registryValue = winreg.QueryValueEx(registryKey, "RemotePath")
        return(registryValue)

#Loop over all drive letters
for letter in ascii_lowercase:
    try:
        drive_path = win32wnet.WNetGetConnection(letter + ":")
    except win32wnet.error as exception:
        #If drive is remembered but unavailable, retrieve path from registry
        if exception.args[2] == "The device is not currently connected but it is a remembered connection.":
            drive_path = getRememberedConnection(letter)

        else:
            pass
Answered By: dustmole