删除与网络共享的连接时如何提供用户名和密码(在C#中)

时间:2012-03-14 09:56:24

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

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

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 * / del / yes(删除所有现有连接)

我尝试此命令但与net use不兼容:

  

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

     

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

有关它的任何建议吗?

1 个答案:

答案 0 :(得分:1)

下面的命令应该适合你;

net use {share_name} / delete

net use \\ Machine1 \ path1 / delete

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

公共类NetworkConnection:IDisposable     {         string _networkName;         private 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