下面的代码用httpwebrequest实现了单个文件的下载:
string savePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"DataBase\Image\test\" + PictureName//本地保存路径
, downFileUrl = "http://www.myserver.com/Image/" + PictureName;//下载文件的链接地址
WebClient wcClient = new WebClient();
WebRequest webReq = WebRequest.Create(downFileUrl);
WebResponse webRes = webReq.GetResponse();
int fileLength = int.Parse(webRes.ContentLength.ToString()); Stream srm = webRes.GetResponseStream();
StreamReader srmReader = new StreamReader(srm);
byte[] bufferbyte = new byte[fileLength];
int allByte = (int)bufferbyte.Length;
int startByte = 0;
while (fileLength > 0)
{
//Application.DoEvents();
int downByte = srm.Read(bufferbyte, startByte, allByte);
if (downByte == 0) { break; };
startByte += downByte;
allByte -= downByte;
} if (!File.Exists(savePath))
{
string[] dirArray = savePath.Split('\\');
string temp = string.Empty;
for (int i = 0; i < dirArray.Length - 1; i++)
{
temp += dirArray[i].Trim() + "\\";
if (!Directory.Exists(temp))
Directory.CreateDirectory(temp);
}
}
FileStream fs = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(bufferbyte, 0, bufferbyte.Length);
srm.Close();
srmReader.Close();
fs.Close();
服务器的Image文件夹下有多个文件,如果一个个地下载,代码太罗嗦,效率也低。怎样写代码,才能一次性、高效率地下载Image文件夹下的所有文件?
谢谢指点!
string savePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"DataBase\Image\test\" + PictureName//本地保存路径
, downFileUrl = "http://www.myserver.com/Image/" + PictureName;//下载文件的链接地址
WebClient wcClient = new WebClient();
WebRequest webReq = WebRequest.Create(downFileUrl);
WebResponse webRes = webReq.GetResponse();
int fileLength = int.Parse(webRes.ContentLength.ToString()); Stream srm = webRes.GetResponseStream();
StreamReader srmReader = new StreamReader(srm);
byte[] bufferbyte = new byte[fileLength];
int allByte = (int)bufferbyte.Length;
int startByte = 0;
while (fileLength > 0)
{
//Application.DoEvents();
int downByte = srm.Read(bufferbyte, startByte, allByte);
if (downByte == 0) { break; };
startByte += downByte;
allByte -= downByte;
} if (!File.Exists(savePath))
{
string[] dirArray = savePath.Split('\\');
string temp = string.Empty;
for (int i = 0; i < dirArray.Length - 1; i++)
{
temp += dirArray[i].Trim() + "\\";
if (!Directory.Exists(temp))
Directory.CreateDirectory(temp);
}
}
FileStream fs = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(bufferbyte, 0, bufferbyte.Length);
srm.Close();
srmReader.Close();
fs.Close();
服务器的Image文件夹下有多个文件,如果一个个地下载,代码太罗嗦,效率也低。怎样写代码,才能一次性、高效率地下载Image文件夹下的所有文件?
谢谢指点!
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货