连接远程共享文件夹
/// <summary>
/// 连接远程共享文件夹
/// </summary>
/// <param name="path">远程共享文件夹的路径</param>
/// <param name="username">用户名</param>
/// <param name="password">密码</param>
/// <returns></returns>
public static bool ConnectState(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="src">下载到本地后文件路径,包含文件扩展名</param>
/// <param name="dst">远程服务器路径(共享文件夹路径)</param>
/// <param name="fileName">远程服务器(共享文件夹)中的文件名称,包含扩展名</param>
public static void TransportRemoteToLocal(string src, string dst, string fileName)
{
if (!Directory.Exists(dst))
{
Directory.CreateDirectory(dst);
}
dst = dst+"\\" + fileName;
FileStream inFileStream = new FileStream(dst, FileMode.Open);
FileStream outFileStream = new FileStream(src, FileMode.OpenOrCreate);
byte[] buf = new byte[inFileStream.Length];
int byteCount;
while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
{
outFileStream.Write(buf, 0, byteCount);
}
inFileStream.Flush();
inFileStream.Close();
outFileStream.Flush();
outFileStream.Close();
}
将本地文件上传到远程服务器共享目录
/// <summary>
/// 将本地文件上传到远程服务器共享目录
/// </summary>
/// <param name="src">本地文件的绝对路径,包含扩展名</param>
/// <param name="dst">远程服务器共享文件路径,不包含文件扩展名</param>
/// <param name="fileName">上传到远程服务器后的文件扩展名</param>
public static void TransportLocalToRemote(string src, string dst, string fileName)
{
FileStream inFileStream = new FileStream(src, FileMode.Open);
//判断上传的远程服务器路径是否存在
if (!Directory.Exists(dst))
{
Directory.CreateDirectory(dst);
}
//上传到远程服务器共享文件夹后文件的绝对路径
dst = dst + fileName;
FileStream outFileStream = new FileStream(dst, FileMode.OpenOrCreate);
byte[] buf = new byte[inFileStream.Length];
int byteCount;
while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
{
outFileStream.Write(buf, 0, byteCount);
}
inFileStream.Flush();
inFileStream.Close();
outFileStream.Flush();
outFileStream.Close();
}