【小5聊】C#基础之调用cmd执行命令并且执行遇到需要输入Y或N的情况

当需要清除共享文件登录用户时,执行第一条命令后,会提示需要输入Y或N,就是是否确认删除,Y=是,N=不

1、通过cmd命令登录共享文件

执行如下代码,会直接弹出无需再登录的共享文件界面 

  • 代码 
using (Process myPro = new Process())
{
    myPro.StartInfo.FileName = "cmd.exe";
    myPro.StartInfo.UseShellExecute = false;
    myPro.StartInfo.RedirectStandardInput = true;
    myPro.StartInfo.RedirectStandardOutput = true;
    myPro.StartInfo.RedirectStandardError = true;
    myPro.StartInfo.CreateNoWindow = true;
    myPro.Start();

    string str = @"net use \\192.168.0.115 这里填密码 /user:这里填用户名 &exit";
    myPro.StandardInput.WriteLine(str);


    myPro.StandardInput.AutoFlush = true;
    myPro.WaitForExit();
}

//再打开调起网络
System.Diagnostics.Process.Start("\\\\192.168.0.115");

 2、先删除再调用

关键代码:echo y

关键代码:net use * /delete /y

执行如下代码后,会弹出如下界面

  • 效果

  • 代码
using (Process myPro = new Process())
{
    myPro.StartInfo.FileName = "cmd.exe";
    myPro.StartInfo.UseShellExecute = false;
    myPro.StartInfo.RedirectStandardInput = true;
    myPro.StartInfo.RedirectStandardOutput = true;
    myPro.StartInfo.RedirectStandardError = true;
    myPro.StartInfo.CreateNoWindow = true;
    myPro.Start();

    string str = @"net use \\192.168.0.115 你的密码 /user:你的账号 &exit";
    //myPro.StandardInput.WriteLine(str);

    执行删除
    str = "echo y net use * /delete";
    //如果不行,那么使用下面这条语句
    //str = "net use * /delete /y";
    myPro.StandardInput.WriteLine(str);

    myPro.StandardInput.AutoFlush = true;
    //myPro.WaitForExit(); //等待进程关闭
}

//再打开调起网络
System.Diagnostics.Process.Start("\\\\192.168.0.115");

猜你喜欢

转载自blog.csdn.net/lmy_520/article/details/120321349