/// <summary>
/// 共享文件操作类
/// </summary>
public class SharedFolderManager
{
public SharedFolderManager()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 共享文件夹根路径
/// </summary>
private static readonly string RootPath = ConfigurationManager.AppSettings["RootPath"];
/// <summary>
/// 连接共享文件夹的账号
/// </summary>
private static readonly string User = ConfigurationManager.AppSettings["User"];
/// <summary>
/// 连接共享文件夹的密码
/// </summary>
private static readonly string Password = ConfigurationManager.AppSettings["Password"];
/// <summary>
/// 连接共享文件夹,连接上后可以像操作本地磁盘的方式操作文件夹和文件
/// 该方法使用配置文件中的信息连接共享文件夹
/// </summary>
/// <returns></returns>
public static bool Connect()
{
return Connect(RootPath, User, Password);
}
/// <summary>
/// 连接共享文件夹,连接上后可以像操作本地磁盘的方式操作文件夹和文件
/// </summary>
/// <param name="path">共享文件夹路径</param>
/// <param name="userName">用户名</param>
/// <param name="passWord">密码</param>
/// <returns>连接成功返回true,否则返回false</returns>
public static bool Connect(string path, 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 " + path + " /User:" + userName + " " + passWord + " /PERSISTENT:YES";
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;
}
/// <summary>
/// 相对共享文件夹根路径的路径
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string GetPath(string path)
{
if (path.StartsWith("\"))
{
path = path.Substring(1);
}
return Path.Combine(RootPath, path);
}
}