Link to home
Create AccountLog in
Avatar of millerje
millerjeFlag for United States of America

asked on

Get mapped network drives on a remote computer

Hi experts,

I have been using a vbscript for a few years now that can get a users mapped network drives remotely.  I have been developing a C# program and am unable to find a good reliable way of accomplishing this.  I am currently using WMI, which works sometimes, but not all the time.  The vbscript looks through the registry and works everytime. I would like to use something like this in my c# program.  I will post the vbscript to this question.  Any help will be greatly appreciated.  The only change in the c# app is that instead of exporting the results to a txt file, I will be appending the results to a rich text box.

' Current User Mapped Drives V1.0

on error resume next

' ********** Get computer name from the user
strComputer=inputbox("Enter Computer Name: ", "Current User Mapped Drives")

' ********** Define constants
Const HKEY_USERS = &H80000003

' ********** Blank the report message
strMsg = ""

' ********** Set objects 
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objWbem = GetObject("winmgmts:")
Set objRegistry = GetObject("winmgmts://" & strComputer & "/root/default:StdRegProv")

if err.number = "-2147217375" then
	' Do nothing
else

	' ********** Check to make sure the computer exists on the network.
	Select Case err.number
		Case 462
			strWarn=MsgBox("Unable to connect to " & strComputer & ".", 48, "System Information Checker")
		Case -2147217394
			strWarn=MsgBox(strComputer & " is not a valid name.", 48, "System Information Checker")
		Case 70
			strWarn=MsgBox(strComputer & " has denied access.", 48, "System Information Checker")
    	Case Else

	' ********** Get the current user from Explorer  

	Set colProc = objWmiService.ExecQuery("Select Name from Win32_Process" & " Where Name='explorer.exe'")

	If colProc.Count > 0 Then
		For Each oProcess In colProc
			oProcess.GetOwner sUser, sDomain
		Next
	End If

	' ********** Print user and computer
	strMsg = strMsg & "    User: " & sUser & VbCrLf
	strMsg = strMsg & "Computer: " & strComputer & VbCrLf & VbCrLf
	

	' ********** Loop through the HKEY_USERS hive until the currently logged on user is matched
	lngRtn = objRegistry.EnumKey(HKEY_USERS, "", arrRegKeys)
	
	For Each strKey In arrRegKeys
		If UCase(strKey) = ".DEFAULT" Or UCase(Right(strKey, 8)) = "_CLASSES" Then
		Else
			Set objSID = objWbem.Get("Win32_SID.SID='" & strKey & "'")
			If objSID.accountname = sUser Then 
				regpath2enumerate = strkey & "\Network" 'strkey is the SID
				objRegistry.enumkey hkey_users, regpath2enumerate, arrkeynames
				
				If Not (IsEmpty(arrkeynames)) Then
					For Each subkey In arrkeynames
						regpath = strkey & "\Network\" & subkey
						regentry = "RemotePath"
						objRegistry.getstringvalue hkey_users, regpath, regentry, dapath
						strMsg = strMsg & subkey & ":" & vbTab & dapath & VbCrLf
					Next
				End If
			End If
		End If
	Next


		' ********** Check for the existence of the "SysInfoCheck" folder then
		' ********** write the file to disk.
		strDirectory = "C:\SysInfoCheck"
		Set objFSO = CreateObject("Scripting.FileSystemObject")
		If objFSO.FolderExists(strDirectory) Then
    			' Procede
		Else
    			Set objFolder = objFSO.CreateFolder(strDirectory)
		End if

		' ********** Calculate date serial for filename **********
		intMonth = month(now)
		if intMonth < 10 then
			strThisMonth = "0" & intMonth
		else
			strThisMonth = intMOnth
		end if
		intDay = Day(now)
		if intDay < 10 then
			strThisDay = "0" & intDay
		else
			strThisDay = intDay
		end if
		strFilenameDateSerial = year(now) & strThisMonth & strThisDay

		Set objFile = objFSO.CreateTextFile(strDirectory & "\" & strComputer & "_" & sUser & "_MappedDrives" & "_" & strFilenameDateSerial & ".txt",True)	
		objFile.Write strMsg & vbCrLf

		' ********** Ask to view file
		strFinish = "Finished collecting mapped drives for computer: " & strComputer & "." & VbCrLf & VbCrLf & "View file?"
		strAnswer=MsgBox(strFinish, 68, "System Information Checker")
		if strAnswer = 6 then
    			Set objShell = CreateObject("WScript.Shell")
    			objShell.run strDirectory & "\" & strComputer & "_" & sUser & "_MappedDrives" & "_" & strFilenameDateSerial & ".txt"
		end if

	end select

end if

Open in new window

Avatar of Gautham Janardhan
Gautham Janardhan

combining (http://stackoverflow.com/questions/1088752/how-to-programmatically-discover-mapped-network-drives-on-system-and-their-serve) and (http://msdn.microsoft.com/en-us/library/ms257337(v=vs.80).aspx)

try
            {
                var searcher = new ManagementObjectSearcher(
                    "\\\\remoteservername\\root\\cimv2",
                    "SELECT * FROM Win32_MappedLogicalDisk");

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Win32_MappedLogicalDisk instance");
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Access: {0}", queryObj["Access"]);
                    Console.WriteLine("Availability: {0}", queryObj["Availability"]);
                    Console.WriteLine("BlockSize: {0}", queryObj["BlockSize"]);
                    Console.WriteLine("Caption: {0}", queryObj["Caption"]);
                    Console.WriteLine("Compressed: {0}", queryObj["Compressed"]);
                    Console.WriteLine("ConfigManagerErrorCode: {0}", queryObj["ConfigManagerErrorCode"]);
                    Console.WriteLine("ConfigManagerUserConfig: {0}", queryObj["ConfigManagerUserConfig"]);
                    Console.WriteLine("CreationClassName: {0}", queryObj["CreationClassName"]);
                    Console.WriteLine("Description: {0}", queryObj["Description"]);
                    Console.WriteLine("DeviceID: {0}", queryObj["DeviceID"]);
                    Console.WriteLine("ErrorCleared: {0}", queryObj["ErrorCleared"]);
                    Console.WriteLine("ErrorDescription: {0}", queryObj["ErrorDescription"]);
                    Console.WriteLine("ErrorMethodology: {0}", queryObj["ErrorMethodology"]);
                    Console.WriteLine("FileSystem: {0}", queryObj["FileSystem"]);
                    Console.WriteLine("FreeSpace: {0}", queryObj["FreeSpace"]);
                    Console.WriteLine("InstallDate: {0}", queryObj["InstallDate"]);
                    Console.WriteLine("LastErrorCode: {0}", queryObj["LastErrorCode"]);
                    Console.WriteLine("MaximumComponentLength: {0}", queryObj["MaximumComponentLength"]);
                    Console.WriteLine("Name: {0}", queryObj["Name"]);
                    Console.WriteLine("NumberOfBlocks: {0}", queryObj["NumberOfBlocks"]);
                    Console.WriteLine("PNPDeviceID: {0}", queryObj["PNPDeviceID"]);

                    if (queryObj["PowerManagementCapabilities"] == null)
                        Console.WriteLine("PowerManagementCapabilities: {0}", queryObj["PowerManagementCapabilities"]);
                    else
                    {
                        UInt16[] arrPowerManagementCapabilities = (UInt16[])(queryObj["PowerManagementCapabilities"]);
                        foreach (UInt16 arrValue in arrPowerManagementCapabilities)
                        {
                            Console.WriteLine("PowerManagementCapabilities: {0}", arrValue);
                        }
                    }
                    Console.WriteLine("PowerManagementSupported: {0}", queryObj["PowerManagementSupported"]);
                    Console.WriteLine("ProviderName: {0}", queryObj["ProviderName"]);
                    Console.WriteLine("Purpose: {0}", queryObj["Purpose"]);
                    Console.WriteLine("QuotasDisabled: {0}", queryObj["QuotasDisabled"]);
                    Console.WriteLine("QuotasIncomplete: {0}", queryObj["QuotasIncomplete"]);
                    Console.WriteLine("QuotasRebuilding: {0}", queryObj["QuotasRebuilding"]);
                    Console.WriteLine("SessionID: {0}", queryObj["SessionID"]);
                    Console.WriteLine("Size: {0}", queryObj["Size"]);
                    Console.WriteLine("Status: {0}", queryObj["Status"]);
                    Console.WriteLine("StatusInfo: {0}", queryObj["StatusInfo"]);
                    Console.WriteLine("SupportsDiskQuotas: {0}", queryObj["SupportsDiskQuotas"]);
                    Console.WriteLine("SupportsFileBasedCompression: {0}", queryObj["SupportsFileBasedCompression"]);
                    Console.WriteLine("SystemCreationClassName: {0}", queryObj["SystemCreationClassName"]);
                    Console.WriteLine("SystemName: {0}", queryObj["SystemName"]);
                    Console.WriteLine("VolumeName: {0}", queryObj["VolumeName"]);
                    Console.WriteLine("VolumeSerialNumber: {0}", queryObj["VolumeSerialNumber"]);
                }
            }
            catch (ManagementException ex)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + ex.Message);
            }

Open in new window

Avatar of millerje

ASKER

I don't want to use WMI, I want to search through the registry like the vbscript I posted. Can someone help convert this to c#?
ASKER CERTIFIED SOLUTION
Avatar of Gautham Janardhan
Gautham Janardhan

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
After reading through the code, it seems like it is the right answer.  I am going to accept this and try to get it to work.  I will post results when I do.  Thanks gauthampj!!