C#访问共享文件夹,并下载数据到本地
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DBHelperWMS
{
public class ShareDownload
{
public bool connectState(string path)
{
return connectState(path, "", "");
}
public 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 + " " + 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;
}
public 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();
}
public 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();
}
}
}
测试访问代码
public void test()
{
bool status = false;
ShareDownload sd = new ShareDownload();
status = sd.connectState(@"\\xxx.xx.x.x\e", "administrator", "123456");
if (status)
{
DirectoryInfo theFolder = new DirectoryInfo(@"\\xxx.xx.x.x\e\");
string filename = theFolder.ToString();
//执行方法
//TransportLocalToRemote(@"D:\readme1.txt", filename, "readme1.txt");
sd.TransportRemoteToLocal(@"D:\123.txt", filename, "123.txt");
}
else
{
MessageBox.Show("未能连接!");
}
MessageBox.Show("成功");
}
原文出处连接:https://blog.csdn.net/liuqinghui1990/article/details/76559721