0

I use the following command for connect to network share:

NET USE \Machine1 /user:MyDomain\MyUser MyPassword

I use C# code programatically (using 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");
                    }
                }

Sometimes, there are any errors like this:

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again.

I want delete the connection (to network share) programatically:

net use (to see all existing connections)

net use * /del /yes (to delete all existing connections)

I try this command but not compatible with net use:

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

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

any suggestions about it?

Kiquenet
  • 14,494
  • 35
  • 148
  • 243

1 Answers1

1

below command should work for you;

net use {share_name} /delete

net use \\Machine1\path1 /delete

And a better solution is to use below class to achieve it.

public class 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
}

from another thread

Community
  • 1
  • 1