在局域网内像处理本地磁盘上的文件一样进行文件的读写操作,有很多方案,
FTP :配置较麻烦,而且是异步传输,传输完成的结果响应比较复杂;
物理映射:需要在本地添加共享用户的账号
Net Use:可以直接使用指定的共享目录账号(不需要在本地创建账号)进行访问,使用此Dos命令建立连接后,就可以直接像本地磁盘文件一样进行操作了。
以下是实现的C#代码
/// <summary>
/// Connet to remote share folder
/// </summary>
/// <param name="remoteHost">remote server IP or machinename.domain name</param>
/// <param name="shareName">share name</param>
/// <param name="userName">user name of remote share access account</param>
/// <param name="passWord">password of remote share access account</param>
/// <returns>connect result</returns>
public static bool Connect(string remoteHost, string shareName, 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 \\" + remoteHost + @"\" + shareName + " /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;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
proc.Close();
proc.Dispose();
}
return Flag;
}
/// Connet to remote share folder
/// </summary>
/// <param name="remoteHost">remote server IP or machinename.domain name</param>
/// <param name="shareName">share name</param>
/// <param name="userName">user name of remote share access account</param>
/// <param name="passWord">password of remote share access account</param>
/// <returns>connect result</returns>
public static bool Connect(string remoteHost, string shareName, 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 \\" + remoteHost + @"\" + shareName + " /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;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
proc.Close();
proc.Dispose();
}
return Flag;
}
在Web site中使用时,只需要在IO操作前,通过WebService来调用上述代码建立连接,就可以像在本地目录一样读写文件了。
来源:https://www.cnblogs.com/litsword/archive/2010/03/04/1678434.html