【问题标题】:How to provide user name and password when Delete connection to a network share (in C#)删除与网络共享的连接时如何提供用户名和密码(在 C# 中)
【发布时间】:2012-03-14 09:56:23
【问题描述】:

我使用以下命令连接到网络共享:

NET USE \Machine1 /user:MyDomain\MyUser MyPassword

我以编程方式使用 C# 代码(使用 Process.Start)

ProcessStartInfo psi = new ProcessStartInfo("NET");

                string[] userTokens = usuario.Split('\\');
                if (userTokens.Length == 2)
                {
                    psi.Arguments = @"USE \\" + maquina + " /user:" + usuario + " " + pwd;
                }
                else
                {
                    psi.Arguments = @"USE \\" + maquina + " /user:" + maquina + "\\" + usuario + " " + pwd;
                }

                psi.UseShellExecute = false;
                psi.ErrorDialog = false;
                psi.RedirectStandardOutput = true;
                //psi.RedirectStandardInput = true;
                psi.RedirectStandardError = true;
                psi.CreateNoWindow = true;

                using (Process pr = Process.Start(psi))
                {
                    //StreamWriter sw = pr.StandardInput;
                    //sw.AutoFlush = true;
                    sr = pr.StandardOutput;
                    serr = pr.StandardError;

                    string salida = "";

                    pr.WaitForExit(300000);
                    salida += sr.ReadToEnd();
                    salida += Environment.NewLine;
                    salida += serr.ReadToEnd();
                    salida += Environment.NewLine;

                    Trace.WriteLine("ConectarServidor. NET USE " + maquina + " " + usuario + Environment.NewLine
                         + " Salida: " + salida.Trim());


                    if (salida.Contains("error 1219")
                        || salida.Contains("Error de sistema 1219"))
                    {
                        // Path is already connected
                        Trace.WriteLine("Error Net Use 1219: Path is already connected");
                        TratamientoErrorNetUse1219(maquina, usuario, pwd);
                    }
                    else if (salida.Contains("error 86"))
                    {
                        //'Incorrect Password
                        Trace.WriteLine("Error Net Use 86: Incorrect Password");
                    }
                }

有时会出现这样的错误:

同一用户与服务器或共享资源的多个连接, 不允许使用多个用户名。断开所有 以前与服务器或共享资源的连接,然后重试。

我想以编程方式删除连接(到网络共享):

net use(查看所有现有连接)

net use * /del /yes(删除所有现有连接)

我尝试了这个命令,但与 net use 不兼容:

NET USE \Machine1 /del /yes /user:MyDomain\MyUser MyPassword

网络使用 * /del /yes /user:MyDomain\MyUser MyPassword

有什么建议吗?

【问题讨论】:

    标签: c# .net networking command-line passwords


    【解决方案1】:

    下面的命令应该适合你;

    net use {share_name} /delete

    net use \\Machine1\path1 /delete

    更好的解决方案是使用下面的类来实现它。

    公共类 NetworkConnection : IDisposable { 字符串_networkName; 私有 bool isLocal = false;

        public NetworkConnection(string networkName,
            NetworkCredential credentials)
        {
            _networkName = networkName;
            if (!_networkName.Contains("\\\\"))
            {
                this.isLocal = true;
                return;
            }
            var netResource = new NetResource()
            {
                Scope = ResourceScope.GlobalNetwork,
                ResourceType = ResourceType.Disk,
                DisplayType = ResourceDisplaytype.Share,
                RemoteName = networkName
            };
    
            var result = WNetAddConnection2(
                netResource,
                credentials.Password,
                credentials.UserName,
                0);
    
            if (result != 0)
            {
                throw new Win32Exception(result, "Error connecting to remote share");
            }
        }
    
        ~NetworkConnection()
        {
            if (!this.isLocal)
            {
                Dispose(false);    
            }
    
        }
    
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    
        protected virtual void Dispose(bool disposing)
        {
            WNetCancelConnection2(_networkName, 0, true);
        }
    
        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2(NetResource netResource,
            string password, string username, int flags);
    
        [DllImport("mpr.dll")]
        private static extern int WNetCancelConnection2(string name, int flags,
            bool force);
    }
    
    [StructLayout(LayoutKind.Sequential)]
    public class NetResource
    {
        public ResourceScope Scope;
        public ResourceType ResourceType;
        public ResourceDisplaytype DisplayType;
        public int Usage;
        public string LocalName;
        public string RemoteName;
        public string Comment;
        public string Provider;
    }
    
    public enum ResourceScope : int
    {
        Connected = 1,
        GlobalNetwork,
        Remembered,
        Recent,
        Context
    };
    
    public enum ResourceType : int
    {
        Any = 0,
        Disk = 1,
        Print = 2,
        Reserved = 8,
    }
    
    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
    }
    

    来自另一个thread

    【讨论】:

      猜你喜欢
      • 2015-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 2016-12-08
      • 2011-04-11
      • 2016-05-29
      • 2021-04-29
      相关资源
      最近更新 更多