2010年12月10日 星期五

[C#] UNC 網路芳鄰連接 含帳號密碼

using IWshRuntimeLibrary;  //在COM 元件內 

private WshNetwork _networkShell = new WshNetwork();
        private void MapDrive(string driveLetter, string UNC, bool isPersistent, string userName, string password)
        {
            if (driveLetter != "")
            {
                DisconnectDrive(driveLetter, true, true);
            }
            else
            {
                DisconnectDrive(UNC, true, true);
            }
            object persistent = isPersistent;
            object user = userName;
            object pwd = password;
            _networkShell.MapNetworkDrive(driveLetter, UNC, ref persistent, ref user, ref pwd);
        }

        private void DisconnectDrive(string UNC_or_DriveName, bool willForce, bool isPersistent)
        {
            try
            {
                object force = willForce;
                object updateProfile = isPersistent;
                _networkShell.RemoveNetworkDrive(UNC_or_DriveName, ref force, ref updateProfile);
            }
            catch
            {
                //
            }
        }

//使用方式 Mount
        private void MAP_DRIVER_Y()
        {
            string sour_path = @"file://123.456.789.123/qq";
            MapDrive("Y:", sour_path, false, "user_id", "password");
        }

// Umount
        private void DIS_MAP_DRIVER_Y()
        {
            DisconnectDrive("Y:", true, true);
        }

不想使用 命令模式 ,這是另一個選擇

沒有留言:

張貼留言