1.根据网络路径下的共享文件夹下载文件。
2.代码
(1)直接下载
WebClient wc = new WebClient()
{
//Credentials = new NetworkCredential("Administrator", "Iphone6")
Credentials = CredentialCache.DefaultCredentials
};
wc.DownloadFile(@"\\192.168.1.131\share\"+filename,@"D:\"+filename);
WebClient的DownloadFile(网络路径位置,待存储位置)
(2)分片下载(可能需要用户名密码认证)
WebClient client = new WebClient()
{
//Credentials = new NetworkCredential("Administrator", "Iphone6")
Credentials = CredentialCache.DefaultCredentials
};
Stream str = client.OpenRead(@"\\192.168.1.131\share\" + filename);
StreamReader reader = new StreamReader(str);
int allmybyte = (int)reader.BaseStream.Length;
byte[] mbyte = new byte[allmybyte];
int length = 4 * 1024 * 1024;
int startmbyte = 0;
while (allmybyte > 0)
{
if (allmybyte<length)
{
length = allmybyte;
}
//Task<int> m = str.ReadAsync(mbyte, startmbyte, length);
int m = str.Read(mbyte, startmbyte, length);
if (m == 0)
break;
startmbyte += m;
allmybyte -= m;
}
reader.Dispose();
str.Dispose();
string path = @"F:\" + filename;
FileStream fstr = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
fstr.Write(mbyte, 0, startmbyte);
fstr.Flush();
fstr.Close();
本文介绍了两种从网络路径下的共享文件夹下载文件的方法:直接下载和分片下载。直接下载使用WebClient的DownloadFile方法,而分片下载则通过读取流并逐片写入目标文件实现,适用于大文件或需要认证的情况。

2565

被折叠的 条评论
为什么被折叠?



