public class ConnectFile
{
/// <summary>
/// 连接远程共享文件夹添加登录凭证
/// 先关闭所有链接:net use * /del /y 不允许一个用户使用一个以上用户名与服务器或共享资源的多重连接
/// </summary>
/// <param name="Ip">服务器Ip</param>
/// <param name="userName">用户名</param>
/// <param name="passWord">密码</param>
/// <returns></returns>
public static bool connectState(string Ip, string userName, string passWord)
{
bool Flag = false;
Process proc = new Process();
try
{
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
string dosLine = "net use " + Ip + " " + passWord + " /user:" + userName;
proc.StandardInput.WriteLine(dosLine);
proc.StandardInput.WriteLine("exit");
while (!proc.HasExited)
{
proc.WaitForExit(1000);
}
string errormsg = proc.StandardError.ReadToEnd();
proc.StandardError.Close();
if (string.IsNullOrEmpty(errormsg))
{
Flag = true;
}
else
{
throw new Exception(errormsg);
}
}
catch (Exception ex)
{
//throw ex;
}
finally
{
proc.Close();
proc.Dispose();
}
return Flag;
}
}