備忘錄_20160105(定位) 修改 回首頁

程式 2019-09-04 05:07:39 1567544859 100
C# 呼叫 cmd 去執行 net use 連線網路磁碟機

C# 呼叫 cmd 去執行 net use 連線網路磁碟機

安裝程式
C# 原始專案



底下是主要程式碼供參考
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace projNetuse
{
    public partial class frmNetuse : Form
    {
        private long m_lTimes = 0;
        private Color m_bgColor = Color.Gray;
        private Random m_rand = new Random();

        public frmNetuse()
        {
            InitializeComponent();
            m_bgColor = btn連線.BackColor;
            btn連線.BackColor = m_bgColor;
            btn中斷.BackColor = m_bgColor;
        }

        private void doCmd(string strCmd)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = @"/c " + strCmd;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
        }

        private void btn連線_Click(object sender, EventArgs e)
        {
            string strCmd = "";
            strCmd = "net use " + tb磁碟代號.Text.Trim() + ": " + tb目標路徑.Text + " \"" + tbPassword.Text + "\" /user:" + tbUsername.Text + " /persistent:no";
            doCmd(strCmd);

            m_bgColor = btn連線.BackColor;
            m_lTimes = 0;
            timer1.Enabled = true;
        }

        private void btn中斷_Click(object sender, EventArgs e)
        {
            string strCmd = "";
            strCmd = "net use " + tb磁碟代號.Text.Trim() + ": /delete";
            doCmd(strCmd);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            bool booStop = false;

            m_lTimes++;

            btn連線.BackColor = Color.FromArgb(m_rand.Next(0, 255), m_rand.Next(0, 255), m_rand.Next(0, 255));
            Application.DoEvents();

            while (true)
            {
                if (m_lTimes > 300)
                {
                    booStop = true;
                    timer1.Enabled = false;
                    MessageBox.Show("抱歉,連線失敗!");
                    break;
                }

                if (Directory.Exists(tb磁碟代號.Text.Trim() + ":\\") == true)
                {
                    booStop = true;
                    timer1.Enabled = false;

                    string strCmd = "";
                    strCmd = "start " + tb磁碟代號.Text + ":\\";
                    doCmd(strCmd);

                    break;
                }

                break;
            }

            if(booStop==true)
            {
                btn連線.BackColor = m_bgColor;
                Application.DoEvents();
            }
        }
    }
}