Using C# how to map a drive with userid and password

Bharat Guru
Bharat Guru used Ask the Experts™
on
How to make a network map drive using c#
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
just like you would use a cmd with net use \\server\share /user:johndoe password, you could use that information to start a process.
Another method would be to use the windows dlls responsible for network mapping (WNetAddConnection in mpr.dll)

Author

Commented:
pls post the sample code
Commented:
If your refer to the example I provided here - http:/Q_28585911.html#a40516795

There is an overload that takes a NetworkCredential object; e.g. -
netConnection = new NetworkConnection(@"\\server\sharename", "Z", new NetworkCredential("userName", "password"));

Open in new window

Here is the complete code from the referenced EE PAQ:
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

namespace EE_Q28585911
{
	class Program
	{
		static void Main(string[] args)
		{
			NetworkConnection netConnection = null;
			try
			{
				netConnection = new NetworkConnection(@"\\benjamin\programming\development", "Z", new NetworkCredential("userName", "password"));
				if (netConnection.MapNetworkDrive())
					Console.WriteLine("Successfully connected {0} to {1}", netConnection.DriveLetter, netConnection.ShareName);
				else
					Console.WriteLine("Could not connect {0} to {1}; {2} [{3}]", netConnection.DriveLetter, netConnection.ShareName, netConnection.Status.Result, netConnection.Status.GetErrorName);
			}
			catch (ArgumentException ex)
			{
				Console.WriteLine("Argument Exception: {0} [{1}]", ex, ex.Message);
			}
			catch (Exception ex)
			{
				Console.WriteLine("Exception: {0} [{1}]", ex, ex.Message);
			}
			Console.ReadLine();

			if (netConnection != null)
			{
				if (netConnection.DisconnectNetworkDrive(true))
					Console.WriteLine("Successfully disconnected {0} from {1}", netConnection.DriveLetter, netConnection.ShareName);
				else
					Console.WriteLine("Could not disconnect {0} from {1}; {2} [{3}]", netConnection.DriveLetter, netConnection.ShareName, netConnection.Status.Result, netConnection.Status.GetErrorName);
				netConnection.Dispose();
				netConnection = null;
			}
			Console.ReadLine();
		}
	}

	class NetworkConnection : IDisposable
	{
		readonly NetworkCredential fCredentials = null;
		readonly string fDriveLetter;
		readonly NativeMethods.NetResource fNetResource = new NativeMethods.NetResource();
		readonly string fShareName;
		ResultWin32 fStatus = new ResultWin32();

		public bool IsDriveMapped 
		{ 
			get 
			{
				DriveInfo[] drives = DriveInfo.GetDrives();
				var drive = (from DriveInfo d in drives where d.DriveType == DriveType.Network && d.Name.Equals(string.Format("{0}\\", fDriveLetter)) select d).FirstOrDefault();
				return drive != null; 
			} 
		}

		public string DriveLetter { get { return fDriveLetter; } }
		public string ShareName { get { return fShareName; } }
		public ResultWin32 Status { get { return fStatus; } }

		public NetworkConnection(string shareName) : this(shareName, null, null) { ;}

		public NetworkConnection(string shareName, NetworkCredential credentials) : this(shareName, null, credentials) { ;}

		public NetworkConnection(string shareName, char driveLetter) : this(shareName, string.Format("{0}:", driveLetter), null) { ;}

		public NetworkConnection(string shareName, char driveLetter, NetworkCredential credentials) : this(shareName, string.Format("{0}:", driveLetter), credentials) { ;}

		public NetworkConnection(string shareName, string driveLetter) : this(shareName, driveLetter, null) { ;}

		public NetworkConnection(string shareName, string driveLetter, NetworkCredential credentials)
		{
			if (!string.IsNullOrEmpty(shareName))
			{
				if (shareName.Contains("\\") && (shareName.LastIndexOf('\\') == shareName.Length - 1))
					shareName = shareName.Substring(0, shareName.Length - 1);
				fShareName = shareName;
			}
			else
				throw new ArgumentException("Share name cannot be null or empty.", "shareName");

			if (!string.IsNullOrEmpty(driveLetter))
			{
				fDriveLetter = driveLetter.Contains(":") && (driveLetter.LastIndexOf(':') == driveLetter.Length - 1) ? driveLetter : string.Format("{0}:", driveLetter);
				if (!fDriveLetter.IsDriveLetter())
					throw new ArgumentException(string.Format("{0} is not a valid drive letter.", fDriveLetter), "driveLetter");
			}

			fNetResource = new NativeMethods.NetResource()
			{
				Scope = NativeMethods.ResourceScope.GlobalNetwork,
				Type = NativeMethods.ResourceType.Disk,
				DisplayType = NativeMethods.ResourceDisplayType.Share,
				LocalName = fDriveLetter,
				RemoteName = fShareName
			};

			fCredentials = credentials;
		}

		~NetworkConnection()
		{
			Dispose(false);
		}

		public bool MapNetworkDrive()
		{
			if (!string.IsNullOrEmpty(fDriveLetter) && IsDriveMapped)
				DisconnectNetworkDrive(true);
			fStatus = new ResultWin32(NativeMethods.WNetAddConnection2(fNetResource, fCredentials != null ? fCredentials.Password : null, fCredentials != null ? fCredentials.UserName : null, 0));
			return fStatus.Result == 0;
		}

		public bool DisconnectNetworkDrive(bool forceDisconnect)
		{
			fStatus = new ResultWin32(NativeMethods.WNetCancelConnection2(fDriveLetter, 0, forceDisconnect));
			return fStatus.Result == 0;
		}

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			DisconnectNetworkDrive(true);
		}
	}

	static class Extensions
	{
		public static bool IsDriveLetter(this string source)
		{
			return new Regex("[d-zD-Z]:").IsMatch(source);
		}
	}

	static class NativeMethods
	{
		[DllImport("mpr.dll", CharSet = CharSet.Unicode)]
		[return: MarshalAs(UnmanagedType.U4)]
		public static extern Int32 WNetAddConnection2
			(
				[In] NetResource lpNetResource, 
				[param: MarshalAs(UnmanagedType.LPTStr), In] string lpPassword, 
				[param: MarshalAs(UnmanagedType.LPTStr), In] string lpUsername, 
				[param: MarshalAs(UnmanagedType.U4), In] Int32 dwFlags
			);

		[DllImport("mpr.dll", CharSet = CharSet.Unicode)]
		[return: MarshalAs(UnmanagedType.U4)]
		public static extern Int32 WNetCancelConnection2
			(
				[param: MarshalAs(UnmanagedType.LPTStr), In] string lpName, 
				[param: MarshalAs(UnmanagedType.U4), In] Int32 dwFlags,
				[param: MarshalAs(UnmanagedType.Bool), In] bool fForce
			);

		public enum ResourceScope : int
		{
			Connected = 1,
			GlobalNetwork,
			Remembered,
			Recent,
			Context
		}

		public enum ResourceType : int
		{
			Any = 0,
			Disk = 1,
			Print = 2,
			Reserved = 8,
			Unknown = -1
		}

		public enum ResourceDisplayType : int
		{
			Generic = 0x0,
			Domain = 0x01,
			Server = 0x02,
			Share = 0x03,
			File = 0x04,
			Group = 0x05,
			Network = 0x06,
			Root = 0x07,
			ShareAdmin = 0x08,
			Directory = 0x09,
			Tree = 0x0a,
			NdsContainer = 0x0b
		}

		[Flags]
		public enum ResourceUsage : int
		{
			Connectable = 1,
			Container = 1 << 1,
			NoLocalDevice = 1 << 2,
			Sibling = 1 << 3,
			Attached = 1 << 4,
			All = Connectable | Container | Attached
		}

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
		public class NetResource
		{
			[MarshalAs(UnmanagedType.U4)]
			private ResourceScope fScope;
			[MarshalAs(UnmanagedType.U4)]
			private ResourceType fType;
			[MarshalAs(UnmanagedType.U4)]
			private ResourceDisplayType fDisplayType;
			[MarshalAs(UnmanagedType.U4)]
			private ResourceUsage fUsage;
			[MarshalAs(UnmanagedType.LPTStr)]
			private string fLocalName;
			[MarshalAs(UnmanagedType.LPTStr)]
			private string fRemoteName;
			[MarshalAs(UnmanagedType.LPTStr)]
			private string fComment;
			[MarshalAs(UnmanagedType.LPTStr)]
			private string fProvider;

			public ResourceScope Scope
			{
				get { return fScope; }
				set { fScope = value; }
			}

			public ResourceType Type
			{
				get { return fType; }
				set { fType = value; }
			}

			public ResourceDisplayType DisplayType
			{
				get { return fDisplayType; }
				set { fDisplayType = value; }
			}

			public ResourceUsage Usage
			{
				get { return fUsage; }
				set { fUsage = value; }
			}

			public string LocalName
			{
				get { return fLocalName; }
				set { fLocalName = value; }
			}

			public string RemoteName
			{
				get { return fRemoteName; }
				set { fRemoteName = value; }
			}

			public string Comment
			{
				get { return fComment; }
				set { fComment = value; }
			}

			public string Provider
			{
				get { return fProvider; }
				set { fProvider = value; }
			}
		}
	}

	class ResultWin32
	{
		readonly int fResult;
		public int Result { get { return fResult; } }

		public ResultWin32() { ;}

		public ResultWin32(int result)
		{
			fResult = result;
		}

		public string GetErrorName
		{
			get
			{
				FieldInfo[] fields = typeof(ResultWin32).GetFields();
				foreach (FieldInfo fi in fields)
					if ((int)fi.GetValue(null) == fResult)
						return fi.Name;

				return string.Empty;
			}
		}
	
		/// <summary>The operation completed successfully.</summary>
		public const int ERROR_SUCCESS = 0;
		public const int CONNECT_UPDATE_PROFILE = 0x1;
		public const int RESOURCETYPE_DISK = 0x1;
		public const int RESOURCETYPE_PRINT = 0x2;
		public const int RESOURCETYPE_ANY = 0x0;
		public const int RESOURCE_CONNECTED = 0x1;
		public const int RESOURCE_REMEMBERED = 0x3;
		public const int RESOURCE_GLOBALNET = 0x2;
		public const int RESOURCEDISPLAYTYPE_DOMAIN = 0x1;
		public const int RESOURCEDISPLAYTYPE_GENERIC = 0x0;
		public const int RESOURCEDISPLAYTYPE_SERVER = 0x2;
		public const int RESOURCEDISPLAYTYPE_SHARE = 0x3;
		public const int RESOURCEUSAGE_CONNECTABLE = 0x1;
		public const int RESOURCEUSAGE_CONTAINER = 0x2;
		public const int ERROR_ACCESS_DENIED = 5;
		public const int ERROR_ALREADY_ASSIGNED = 85;
		public const int ERROR_BAD_DEV_TYPE = 66;
		public const int ERROR_BAD_DEVICE = 1200;
		public const int ERROR_BAD_NET_NAME = 67;
		public const int ERROR_BAD_PROFILE = 1206;
		public const int ERROR_BAD_PROVIDER = 1204;
		public const int ERROR_BUSY = 170;
		public const int ERROR_CANCELLED = 1223;
		public const int ERROR_CANNOT_OPEN_PROFILE = 1205;
		public const int ERROR_DEVICE_ALREADY_REMEMBERED = 1202;
		public const int ERROR_DEVICE_IN_USE = 2404;
		public const int ERROR_EXTENDED_ERROR = 1208;
		public const int ERROR_INVALID_PASSWORD = 86;
		public const int ERROR_NO_NET_OR_BAD_PATH = 1203;
		public const int ERROR_NOT_CONNECTED = 2250;
		public const int ERROR_OPEN_FILES = 2401;
	}
}

Open in new window


-saige-

Author

Commented:
thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial