[Tutor] getUncPath(mappedDrive)

Tim Golden mail at timgolden.me.uk
Sat Mar 24 23:25:39 CET 2012


On 24/03/2012 21:29, Albert-Jan Roskam wrote:
>     Thanks! This seems a feasible approach. I have found this Python
>     project that exposes some of the functions of mpr.dll:
>     http://sourceforge.net/projects/wnetconnect/ WNetGetConnection is
>     not among the functions, but the code will help. I have to read up
>     on ctypes.Structure though as I never really understood this.

This particular function call doesn't require too much work
in fact. Something like the following code -- error-handling
mostly omitted -- should do the trick:

<code>
import ctypes
#
# Get the ANSI version of the function from its DLL
#
WNetGetConnection = ctypes.windll.mpr.WNetGetConnectionA

ERROR_MORE_DATA = 234

#
# Set up the drive name to map back from
# and an empty buffer with zero length.
#
local_name = "Z:"
length = ctypes.c_long (0)
remote_name = ctypes.create_string_buffer ("")

#
# Call the function, expecting to receive an ERROR_MORE_DATA
# result, which indicates that the buffer is too small and
# which populates the length field with the right length.
#
result = WNetGetConnection (
   local_name,
   remote_name,
   ctypes.byref (length)
)
#
# Assuming we did get that error, recreate the buffer and
# call again with the supplied length. This isn't strictly
# necessary (you could probably get away with hard-coding
# 2048 or whatever) but it does save you having to guess.
#
if result == ERROR_MORE_DATA:
   remote_name = ctypes.create_string_buffer (length.value)
   result = WNetGetConnection (
     local_name,
     remote_name,
     ctypes.byref (length)
   )

#
# If the result of either call was an error, raise an Exception
#
if result != 0:
   raise RuntimeError ("Error %d" % result)

print "Remote name is", remote_name.value

</code>

TJG


More information about the Tutor mailing list