コード例 #1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        #region netdrive
        NetworkDrive oNetDrive = new NetworkDrive();
        oNetDrive.LocalDrive      = "M:";
        oNetDrive.Persistent      = true;
        oNetDrive.SaveCredentials = true;
        oNetDrive.ShareName       = @"\\172.16.12.62\cf";

        try
        {
            oNetDrive.MapDrive(@"T1FAB\t1eda", "CIMabc123");

            Parser_tmp_directory_file(oNetDrive.LocalDrive + "\\T1\\AOI\\EDANG\\", "*.TXT", -1);
            Delete_tmp_directory(HttpContext.Current.Server.MapPath(".") + "\\NG_FILE\\", -3);
            oNetDrive.UnMapDrive(oNetDrive.LocalDrive, true);
        }
        catch (Exception)
        {
            oNetDrive.UnMapDrive(oNetDrive.LocalDrive, true);
        }
        finally
        {
            //oNetDrive.UnMapDrive();
        }


        //oNetDrive.MapDrive(@"T1FAB\t1eda", "CIMabc123");
        #endregion


        //oNetDrive.UnMapDrive();
        //Delete_tmp_directory_file(HttpContext.Current.Server.MapPath(".") + "\\NG_FILE\\", "*.TXT", -3);
    }
コード例 #2
0
        public static void RecordSecurityData(DirectoryInfo di, List <DirSec> dirs, string path, string fullPath)
        {
            DirSec            me = new DirSec(fullPath);
            DirectorySecurity ds;
            NetworkDrive      nd = null;

            if (path.Length <= 248)
            {
                ds = Directory.GetAccessControl(path);
            }
            else
            {
                nd            = new NetworkDrive();
                nd.LocalDrive = "X:";
                nd.ShareName  = path;
                nd.MapDrive();
                path = @"X:\";
                di   = new DirectoryInfo(path);
                ds   = Directory.GetAccessControl(path);
            }
            foreach (AuthorizationRule ar in ds.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
            {
                me.AddUser(ar.IdentityReference.Value);
            }
            dirs.Add(me);
            foreach (DirectoryInfo child in di.GetDirectories())
            {
                RecordSecurityData(child, dirs, path + @"\" + child.Name, fullPath + @"\" + child.Name);
            }
            if (nd != null)
            {
                nd.UnMapDrive();
            }
        }
コード例 #3
0
        void AsyncConnectDrive(object obj)
        {
            NetworkDrive drive = (NetworkDrive)obj;

            try
            {
                try
                {
                    ConnectDrive(drive);
                }
                catch (Exception ex)
                {
                    log.Error("Unhandled Exception in BackgroundDriveManager.ConnectDrive: " + ex.Message + " (" + ex.GetType().Name + ")", ex);
                }

                lock (this.activeDrives)
                    if (this.activeDrives.Contains(drive))
                    {
                        this.activeDrives.Remove(drive);
                    }
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                log.Error("Unhandled Exception in BackgroundDriveManager.AsyncConnectDrive: " + ex.Message + " (" + ex.GetType().Name + ")", ex);
            }
        }
コード例 #4
0
        public static void DisconnectNetworkDrive(string strLocalDrive)     // Overload #2
        {
            NetworkDrive drive = new NetworkDrive();

            drive.LocalDrive = strLocalDrive;   // e.g. @"z:"
            DisconnectNetworkDrive(drive);
        }
コード例 #5
0
ファイル: frmTest.cs プロジェクト: Thoth0/NetworkDrive
        private void Button3_Click_1(object sender, System.EventArgs e)
        {
            NetworkDrive oNetDrive = new NetworkDrive();

            ZUpdateStatus("Mapping drive...");
            try {
                //set propertys
                oNetDrive.Force                = this.conForce.Checked;
                oNetDrive.Persistent           = this.conPersistant.Checked;
                oNetDrive.LocalDrive           = txtDrive.Text;
                oNetDrive.PromptForCredentials = conPromptForCred.Checked;
                oNetDrive.ShareName            = txtAddress.Text;
                oNetDrive.SaveCredentials      = conSaveCred.Checked;
                //match call to options provided
                if (txtPassword.Text == "" && txtUsername.Text == "")
                {
                    oNetDrive.MapDrive();
                }
                else if (txtUsername.Text == "")
                {
                    oNetDrive.MapDrive(txtPassword.Text);
                }
                else
                {
                    oNetDrive.MapDrive(txtUsername.Text, txtPassword.Text);
                }
                //update status
                ZUpdateStatus("Drive map successful");
            } catch (Exception err) {
                //report error
                ZUpdateStatus("Cannot map drive! - " + err.Message);
                MessageBox.Show(this, "Cannot map drive!\nError: " + err.Message);
            }
            oNetDrive = null;
        }
コード例 #6
0
ファイル: Server.cs プロジェクト: hungud/MemCacheDManager-1
        private string MapNetworkDrive(string networkPath, string userName, string password)
        {
            string nextDriveLetter = FindNextAvailableDriveLetter();

            NetworkDrive networkDrive = new NetworkDrive();

            networkDrive.LocalDrive      = nextDriveLetter + ":";
            networkDrive.ShareName       = networkPath;
            networkDrive.SaveCredentials = false;
            networkDrive.Persistent      = false;
            networkDrive.MapDrive(userName, password);


            //ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", string.Format("/C NET USE {0}: \"{1}\" {2} /USER:{3}",
            //    nextDriveLetter,
            //    networkPath,
            //    password,
            //    userName));

            //processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            //processStartInfo.CreateNoWindow = true;
            //processStartInfo.UseShellExecute = true;

            //Process mapDriveProcess = Process.Start(processStartInfo);
            //mapDriveProcess.WaitForExit();

            return(nextDriveLetter);
        }
コード例 #7
0
 /// <summary>
 /// Removes a drive from the list and releases the lock.
 /// </summary>
 /// <param name="drive">Drive to remove.</param>
 public void RemoveAndUnlock(NetworkDrive drive)
 {
     lock (this.drives)
         if (this.drives.Contains(drive))
         {
             this.drives.Remove(drive);
         }
 }
コード例 #8
0
 /// <summary>
 /// Removes a drive from the list.
 /// Throws a DriveLockedException when the drive is currently locked.
 /// </summary>
 /// <param name="drive">Drive to remove.</param>
 /// <param name="waitForUnlock">When set to true, this method will wait for a lock to be removed instead of throwing an exception.</param>
 public void RemoveDrive(NetworkDrive drive, bool waitForUnlock = false)
 {
     lock (this.drives)
         if (this.drives.Contains(drive))
         {
             this.drives.Remove(drive);
         }
 }
コード例 #9
0
        private void conMenu_Dialog2_Click(object sender, System.EventArgs e)
        {
            //show the disconnection dialog
            NetworkDrive oNetDrive = new NetworkDrive();

            oNetDrive.ShowDisconnectDialog(this);
            oNetDrive = null;
        }
コード例 #10
0
 static void DisconnectTest(NetworkDrive drive)
 {
     Console.WriteLine("Press any key to disconnect...");
     Console.ReadKey();
     Console.WriteLine("Disconnecting...");
     drive.Disconnect();
     Console.WriteLine("Disconnected: {0}", !drive.IsConnected);
 }
コード例 #11
0
        //Drive tests
        static void DriveTest(NetworkDrive drive)
        {
            Console.WriteLine("--------- DRIVE TEST ({0}) ---------", drive.Address);

            ConnectTest(drive);
            DisconnectTest(drive);

            Console.WriteLine("--------- DRIVE TEST ENDED ---------");
        }
コード例 #12
0
ファイル: MainForm.cs プロジェクト: 0xFireball/FireCrypt
 void TryUnlockVolume()
 {
     //pictureBox1.Visible = true;
     try
     {
         string pass = textBox1.Text;
         currentVolume.UnlockVolume(pass);
         label5.Text = "Successfully Unlocked.";
         if (checkBox1.Checked)
         {
             currentVolume.NetworkDriveMap           = new NetworkDrive();
             currentVolume.NetworkDriveMap.ShareName = NetworkDrive.ConvertToUNCPath(currentVolume.UnlockPath);
             //string mdl = GetFreeDriveLetters()[0]+":"; //map drive letter
             string mdl = freeDriveLetters[comboBox1.SelectedIndex] + ":";                   //map drive letter
             currentVolume.NetworkDriveMap.LocalDrive = mdl;
             try
             {
                 currentVolume.NetworkDriveMap.MapDrive();
                 System.Diagnostics.Process.Start(mdl);
             }
             catch (System.ComponentModel.Win32Exception w3e)
             {
                 MessageBox.Show(w3e.ToString());
             }
         }
         else
         {
             System.Diagnostics.Process.Start(currentVolume.UnlockPath);
         }
     }
     catch (System.Reflection.TargetInvocationException ex)
     {
         try
         {
             throw ex.InnerException;
         }
         catch (NullReferenceException)
         {
             MessageBox.Show("Please select a volume.");
         }
     }
     catch (System.IO.InvalidDataException)
     {
         label5.Text = "Incorrect Password.";
     }
     catch (CryptographicException ce)
     {
         label5.Text = "Incorrect Password.";
     }
     catch (Exception e)
     {
         MessageBox.Show(e.ToString());
         label5.Text = "Unknown Decryption Error. Check your password.";
     }
     //pictureBox1.Visible = false;
     UpdateCurrentItem();
 }
コード例 #13
0
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            HashSet <char> usedLetters   = new HashSet <char>();
            bool           missingLetter = false;
            bool           conflict      = false;

            foreach (DriveListEntry entry in this.drives)
            {
                if (entry.IsChecked)
                {
                    if (entry.DriveConf.DriveLetter < 'A' || entry.DriveConf.DriveLetter > 'Z')
                    {
                        missingLetter = true;
                    }

                    if (usedLetters.Contains(entry.DriveConf.DriveLetter))
                    {
                        conflict = true;
                    }
                    else
                    {
                        usedLetters.Add(entry.DriveConf.DriveLetter);
                    }
                }
            }

            if (missingLetter)
            {
                MessageBox.Show(Properties.Strings.InitialConfigWindowMissingDriveLetterMessage, this.Title, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }

            if (conflict)
            {
                MessageBox.Show(Properties.Strings.InitialConfigWindowLettersConflictMessage, this.Title, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }

            if (usedLetters.Count == 0)
            {
                if (MessageBox.Show(Properties.Strings.InitialConfigWindowNoDrivesMessage, this.Title, MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) != MessageBoxResult.Yes)
                {
                    return;
                }
            }

            foreach (DriveListEntry entry in this.drives)
            {
                if (entry.IsChecked)
                {
                    NetworkDrive drive = new NetworkDrive(entry.DriveConf.DriveLetter.ToString(), entry.DriveConf.DriveLabel, entry.DriveConf.RemoteAddress, null, (SecureString)null);
                    targetList.Add(drive);
                }
            }
            this.DialogResult = true;
            this.Close();
        }
コード例 #14
0
        public static async Task ConnectDrive(IAccesoUPVService service, ConnectionEventArgs e)
        {
            NetworkDrive networkDrive = e.Connectable as NetworkDrive;

            try
            {
                await e.ConnectionFunc();
            }
            catch (NotAvailableDriveException ex) when(ex.Letter == default)
            {
                MessageBox.Show(ex.Message, "Ninguna unidad disponible", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (NotAvailableDriveException ex)
            {
                string WARNING_W =
                    ex.Message + "\n" +
                    "(Continúe si prefiere que se elija la primera unidad disponible solo durante esta conexión).\n ";

                MessageBoxResult result = MessageBox.Show(WARNING_W, $"Unidad {ex.Letter} contiene disco",
                                                          MessageBoxButton.OKCancel, MessageBoxImage.Warning);

                if (result == MessageBoxResult.OK)
                {
                    networkDrive.Letter = default;
                    await e.ConnectionFunc().ContinueWith((t) => networkDrive.Letter = ex.Letter);
                }
            }
            catch (ArgumentNullException ex) when(ex.ParamName.Equals(nameof(networkDrive.Username)))
            {
                MessageBox.Show("No ha indicado ningún nombre de usuario. Indique uno en los ajustes.", "Falta usuario",
                                MessageBoxButton.OK, MessageBoxImage.Warning);
                OpenPreferences(service);
            }
            catch (ArgumentNullException ex) when(ex.ParamName.Equals(nameof(networkDrive.Password)))
            {
                MessageBox.Show("No ha indicado ninguna contraseña. Indíquela en los ajustes.", "Falta contraseña",
                                MessageBoxButton.OK, MessageBoxImage.Warning);
                OpenPreferences(service);
            }
            catch (ArgumentOutOfRangeException ex) when(ex.ParamName.Equals(nameof(networkDrive.Address)))
            {
                /**
                 * We dont ask the user for the address, but the address depends on the username
                 * (which is, in fact, asked to the user). So we assume the error is because of the username.
                 */
                MessageBox.Show("Nombre de usuario incorrecto.", "Usuario incorrecto",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                OpenPreferences(service);
            }
            catch (ArgumentException ex) when(ex.ParamName.Equals(nameof(networkDrive.Password)))
            {
                MessageBox.Show("Contraseña incorrecta.", "Contraseña incorrecta",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                OpenPreferences(service);
            }
        }
コード例 #15
0
        private void RenewDrivePassword(NetworkDrive drive)
        {
            renewDriveMutex.WaitOne();

            try
            {
                bool keepAsking = true;
                do
                {
                    App.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        CredentialsWindow dialog = new CredentialsWindow();
                        dialog.Description       = string.Format(Properties.Strings.CredentialsWindowReEnterAfterFailDescription, Helper.GetDomain(drive.RemoteAddress), AskForCredentialsAfterFails);
                        dialog.Username          = drive.Username;
                        if (dialog.ShowDialog() == true)
                        {
                            drive.SetCredentials(dialog.Username, dialog.Password);
                        }
                        else
                        {
                            keepAsking = false;
                        }
                    }));

                    if (keepAsking)
                    {
                        if (CheckNetworkDrive(drive))
                        {
                            try
                            {
                                drive.Connect(ConnectDriveFlags.IgnoreAlreadyConnected | ConnectDriveFlags.Force);
                            }
                            catch (Exception ex)
                            {
                                this.log.Warn("Could not connect drive \"" + drive.LocalDriveLetter + "\" after password renewal: " + ex.Message, ex);
                                App.Current.Dispatcher.Invoke(new Action(() =>
                                {
                                    MessageBox.Show(null, string.Format(Properties.Strings.MessageConnectFailedAfterCheck), Properties.Strings.TitleCheckConnection, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                                }));
                            }
                            keepAsking = false;
                        }
                    }
                } while (keepAsking);

                App.Current.DriveCollection.SaveDrives();
            }
            catch (Exception ex)
            {
                this.log.Info("Could not renew password for drive \"" + drive.LocalDriveLetter + "\": " + ex.Message, ex);
            }

            renewDriveMutex.ReleaseMutex();
        }
コード例 #16
0
 internal static void CanBeDisconnected(NetworkDrive drive)
 {
     try
     {
         drive.Disconnect();
         ConnectionAsserts.Assert_Disconnected(drive);
     }
     catch (OperationCanceledException)
     {
         ConnectionAsserts.Assert_Connected(drive);
     }
 }
コード例 #17
0
        public async Task WDriveCanBeConnectedAsync()
        {
            // Arrange
            IAccesoUPVService service = new AccesoUPVService();
            NetworkDrive      drive   = service.Disco_W;

            drive.Username = SharedData.Username;
            // Keep to disconnect in further testing
            WDrive = drive;
            // Act and Assert
            await ConnectionTestsAsync.CanBeConnectedAsync(drive);
        }
コード例 #18
0
        internal static async Task CanBeDisconnectedAsync(NetworkDrive drive)
        {
            try
            {
                await drive.DisconnectAsync();

                ConnectionAsserts.Assert_Disconnected(drive);
            }
            catch (OperationCanceledException)
            {
                ConnectionAsserts.Assert_Connected(drive);
            }
        }
コード例 #19
0
        public void DSICDriveCanBeConnected()
        {
            // Arrange
            IAccesoUPVService service = new AccesoUPVService();
            NetworkDrive      drive   = service.Disco_DSIC;

            drive.Username = SharedData.Username;
            drive.Password = SharedData.DSICDrivePass;
            // Keep to disconnect in further testing
            DSICDrive = drive;
            // Act and Assert
            ConnectionTests.CanBeConnected(drive);
        }
コード例 #20
0
ファイル: App.xaml.cs プロジェクト: fakhreddine/KrausRGA
 /// <summary>
 /// Map the network drive to the System.
 /// </summary>
 private void MapDrive()
 {
     try
     {
         NetworkDrive drive = new NetworkDrive();
         drive.Force           = true;
         drive.LocalDrive      = "X:";
         drive.ShareName       = @"\\192.168.1.172\Macintosh HD\ftp_share\RGAImages";
         drive.SaveCredentials = true;
         drive.MapDrive("mediaserver", "kraus2013");
     }
     catch (Exception)
     {}
 }
コード例 #21
0
ファイル: MapDrive.cs プロジェクト: SteveMoody73/Amleto
 public bool Unmount()
 {
     try
     {
         NetworkDrive netDrive = new NetworkDrive();
         netDrive.Drive = Drive.Substring(0, 2);
         netDrive.UnMapDrive();
         return true;
     }
     catch (Exception ex)
     {
         logger.Error(ex, "Unable to unmount the network drive");
     }
     return false;
 }
コード例 #22
0
        static void Main(string[] args)
        {
            string[] paths = { @"K:\PROD\WNT\LIB", @"C:\PERL\V510\BIN", @"C:\LOCALAPPS\BIN", @"K:\PROD\SHARE\BIN", @"K:\PROD\WNT\BIN" };
            SetTechAppsENV.Add("path", paths, EnvironmentVariableTarget.Machine);

            NetworkDrive.SetDrive("K:", @"\\utcapp.com\utas_apps");

            //Installer.Start("Goodrich", "goodrich",@"K:\");
            //Installer.Start("BTA", "bta", @"K:\");
            Installer.Start("IP config", "ipconfig", @"K:\");


            //Thread.Sleep(2000);
            Console.Read();
        }
コード例 #23
0
ファイル: frmTest.cs プロジェクト: Thoth0/NetworkDrive
        private void ConMenu_RestoreAll_Click(object sender, System.EventArgs e)
        {
            NetworkDrive oNetDrive = new NetworkDrive();

            try{
                ZUpdateStatus("Restoring drive connections...");
                oNetDrive.RestoreDrives();
                //update status
                ZUpdateStatus("Drive connections restore successful");
            }catch (Exception err) {
                //report error
                ZUpdateStatus("Error! - " + err.Message);
                MessageBox.Show(this, "Error!\nError: " + err.Message);
            }
            oNetDrive = null;
        }
コード例 #24
0
 /// <summary>
 /// Returns true, when this instance of NetworkDriveCollection contains a drive with the same remote address.
 /// Ignores ignoreDrive in the comparison.
 /// </summary>
 /// <param name="remoteAddress">Remote address to search for.</param>
 /// <param name="ignoreDrive">Drive to ignore in the comparison.</param>
 /// <returns></returns>
 public bool RemoteAddressExists(string remoteAddress, NetworkDrive ignoreDrive = null)
 {
     lock (this.drives)
     {
         foreach (NetworkDrive drive in this.drives)
         {
             if (drive != ignoreDrive)
             {
                 if (drive.RemoteAddress.Equals(remoteAddress, StringComparison.InvariantCultureIgnoreCase))
                 {
                     return(true);
                 }
             }
         }
     }
     return(false);
 }
コード例 #25
0
 private void CheckDriveConnectivity(NetworkDrive drive)
 {
     if (drive.TargetConnectivity)
     {
         if (!drive.IsConnected)
         {
             this.log.Info("Drive \"" + drive.LocalDriveLetter + "\" lost it's connection to \"" + drive.RemoteAddress + "\" -> Restoring...");
             try
             {
                 drive.Connect(ConnectDriveFlags.IgnoreAlreadyConnected | ConnectDriveFlags.Force | ConnectDriveFlags.DoNotUpdateTargetState | ConnectDriveFlags.NoTimeout);
             }
             catch (WNetApiException ex)
             {
                 this.log.Error("Windows-API returned " + ex.ErrorCode + " for drive \"" + drive.LocalDriveLetter + "\": " + ex.Message);
             }
         }
     }
 }
コード例 #26
0
ファイル: Server.cs プロジェクト: hungud/MemCacheDManager-1
        private void UnmapNetworkDrive(string mappedDriveLetter)
        {
            NetworkDrive networkDrive = new NetworkDrive();

            networkDrive.LocalDrive = mappedDriveLetter + ":";
            networkDrive.Force      = true;
            networkDrive.UnMapDrive();

            //ProcessStartInfo processStartInfo = new ProcessStartInfo("CMD.EXE", string.Format("/C NET USE /D {0}:",
            //    mappedDriveLetter));

            //processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            //processStartInfo.CreateNoWindow = true;
            //processStartInfo.UseShellExecute = true;

            //Process unmapDriveProcess = Process.Start(processStartInfo);
            //unmapDriveProcess.WaitForExit();
        }
コード例 #27
0
ファイル: frmTest.cs プロジェクト: Thoth0/NetworkDrive
        private void Button4_Click(object sender, System.EventArgs e)
        {
            NetworkDrive oNetDrive = new NetworkDrive();

            ZUpdateStatus("Unmapping drive...");
            try {
                //unmap the drive
                oNetDrive.Force      = conForce.Checked;
                oNetDrive.LocalDrive = txtDrive.Text;
                oNetDrive.UnMapDrive();
                //update status
                ZUpdateStatus("Drive unmap successful");
            } catch (Exception err) {
                //report error
                ZUpdateStatus("Cannot unmap drive! - " + err.Message);
                MessageBox.Show(this, "Cannot unmap drive!\nError: " + err.Message);
            }
            oNetDrive = null;
        }
コード例 #28
0
        /// <summary>
        /// Clear the current drive collection and reload drives from the default drive location (NetworkDrive.GetDefaultDrivesStoragePath).
        /// </summary>
        public void LoadDrives()
        {
            lock (this.drives)
            {
                this.drives.Clear();

                JArray config = Helper.SafeReadConfig <JArray>(GetDefaultDrivesStoragePath(), GetDefaultDrivesBackupPath());

                if (config != null)
                {
                    bool requireSave;
                    this.drives.AddRange(NetworkDrive.FromArray(config, out requireSave));
                    if (requireSave)
                    {
                        // plaintext values have been found in the configuration => save again to encrypt them
                        SaveDrives();
                    }
                }
            }
        }
コード例 #29
0
ファイル: MapDrive.cs プロジェクト: SteveMoody73/Amleto
 public string Mount()
 {
     string res = "";
     try
     {
         NetworkDrive netDrive = new NetworkDrive();
         netDrive.Drive = Drive.Substring(0, 2);
         netDrive.ShareName = Share;
         if (Username != "")
             netDrive.MapDrive(Username, Password);
         else
             netDrive.MapDrive();
     }
     catch (Exception ex)
     {
         res = ex.Message;
         logger.Error(ex, "Unable to mount the network drive");
     }
     return res;
 }
コード例 #30
0
        private bool CheckNetworkDrive(NetworkDrive drive)
        {
            bool result = false;

            LoadingWindow.TryShowLoadingWindow(Properties.Strings.ProgressMessageCheckingConnection, new Action(() =>
            {
                Exception ex;
                result = drive.CheckConnection(out ex);
                if (!result)
                {
                    log.Error("Connection check of \"" + drive.LocalDriveLetter + "\" to \"" + drive.ExpandedRemoteAddress + "\" with user \"" + drive.Username + "\" failed: " + ex.Message + " (" + ex.GetType().Name + ")", ex);
                    App.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        MessageBox.Show(LoadingWindow.GetStaticLoadingWindow(), string.Format(Properties.Strings.MessageCouldNotConnect, drive.LocalDriveLetter, Helper.GetUserMessage(ex)), Properties.Strings.TitleCheckConnection, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    }));
                }
            }));

            return(result);
        }
コード例 #31
0
        // Mapping and disconnecting network drives

        public static NetworkDrive MapNetworkDrive( // Overload #1
            string strLocalDrive,                   // The first character of strLocalDrive is used as the logical drive letter.
            string strShareName, string strUserName, string strPassword)
        {
            const string strForbiddenDriveLetters = @"abcdef";  // These letters must all be lower case.
            char         cDriveLetter             = strLocalDrive[0];

            if (strForbiddenDriveLetters.IndexOf(cDriveLetter) >= 0 ||
                strForbiddenDriveLetters.ToUpper().IndexOf(cDriveLetter) >= 0)
            {
                throw new Exception(@"'" + cDriveLetter.ToString() + @"' is not an acceptable mapped drive letter in the DAM system.");
            }

            NetworkDrive drive = new NetworkDrive();

            drive.LocalDrive = strLocalDrive;   // e.g. @"z:"
            drive.ShareName  = strShareName;    // e.g. @"\\ComputerName\ShareName"
            drive.MapDrive(strUserName, strPassword);
            return(drive);
        }
コード例 #32
0
        /// <summary>
        /// Returns true, when the given drive letter is neither used by another windows drive nor a managed network drive.
        /// </summary>
        /// <param name="letter">Drive letter to check.</param>
        /// <param name="ignore">NetworkDrive from this collection to ignore. Can be null.</param>
        /// <returns></returns>
        public bool IsDriveLetterAvailable(char letter, NetworkDrive ignore = null)
        {
            // all letters from A to Z are allowed (upper case only)
            letter = char.ToUpper(letter);
            if (letter < 'A' || letter > 'Z')
            {
                return(false);
            }

            // check for existing drives in the system
            foreach (DriveInfo drive in DriveInfo.GetDrives())
            {
                char driveLetter = char.ToUpper(drive.Name[0]);
                if (ignore == null || letter != ignore.LocalDriveLetter[0])
                {
                    if (driveLetter == letter)
                    {
                        return(false);
                    }
                }
            }

            lock (this.drives)
            {
                // check managed network drives (might contain some currently not connected drives)
                foreach (NetworkDrive drive in this.drives)
                {
                    char driveLetter = char.ToUpper(drive.LocalDriveLetter[0]);
                    if (ignore == null || letter != ignore.LocalDriveLetter[0])
                    {
                        if (driveLetter == letter)
                        {
                            return(false);
                        }
                    }
                }
            }

            // letter can be used
            return(true);
        }
コード例 #33
0
ファイル: Server.cs プロジェクト: tekintian/MemCacheDManager
        private string MapNetworkDrive(string networkPath, string userName, string password)
        {
            string nextDriveLetter = FindNextAvailableDriveLetter();

            NetworkDrive networkDrive = new NetworkDrive();
            networkDrive.LocalDrive = nextDriveLetter + ":";
            networkDrive.ShareName = networkPath;
            networkDrive.SaveCredentials = false;
            networkDrive.Persistent = false;
            networkDrive.MapDrive(userName, password);

            //ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", string.Format("/C NET USE {0}: \"{1}\" {2} /USER:{3}",
            //    nextDriveLetter,
            //    networkPath,
            //    password,
            //    userName));

            //processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            //processStartInfo.CreateNoWindow = true;
            //processStartInfo.UseShellExecute = true;

            //Process mapDriveProcess = Process.Start(processStartInfo);
            //mapDriveProcess.WaitForExit();

            return nextDriveLetter;
        }
コード例 #34
0
ファイル: Tree.cs プロジェクト: GreysonT/Script__
        /// <summary>
        /// Analyze wether the root folder is a UNC Path or a local drive
        /// if it is a UNC path it will map it on first available drive.
        /// if a drive is not available it waits until one is available
        /// remove ending backslash '\' for formating and consistency purpose 
        /// </summary>
        private void initProcess()
        {
            if (this.rootFolder.StartsWith(@"\\"))
            {
                string tmp = NetworkDrive.nextFreeDrive();
                while (tmp == "")
                {
                    Thread.Sleep(10000);
                    tmp = NetworkDrive.nextFreeDrive();
                    Console.WriteLine("- " + this.rootFolder + " waiting for free drive");
                }
                try
                {
                    drive = new NetworkDrive();
                    drive.MapDrive(tmp, this.rootFolder, false);
                    Console.WriteLine("- Connecting drive " + drive.LocalDrive + " on " + this.rootFolder);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("-- Connection error ! " + ex.Message);
                }
            }

            if (this.rootFolder.EndsWith(@"\"))
                this.rootFolder = this.rootFolder.Substring(0, this.rootFolder.Length - 1);

            this.processedFolder = (this.drive != null) ? drive.LocalDrive : this.rootFolder;
        }
コード例 #35
0
ファイル: Server.cs プロジェクト: tekintian/MemCacheDManager
        private void UnmapNetworkDrive(string mappedDriveLetter)
        {
            NetworkDrive networkDrive = new NetworkDrive();
            networkDrive.LocalDrive = mappedDriveLetter + ":";
            networkDrive.Force = true;
            networkDrive.UnMapDrive();

            //ProcessStartInfo processStartInfo = new ProcessStartInfo("CMD.EXE", string.Format("/C NET USE /D {0}:",
            //    mappedDriveLetter));

            //processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            //processStartInfo.CreateNoWindow = true;
            //processStartInfo.UseShellExecute = true;

            //Process unmapDriveProcess = Process.Start(processStartInfo);
            //unmapDriveProcess.WaitForExit();
        }