下面是我找的下载文件的代码:HttpWebRequest request;
string tempPath = "d:\\" + textBox1.Text.Substring(textBox1.Text.LastIndexOf("/") + 1);
string updateFileUrl = textBox1.Text;
long fileLength = 0;
request = (HttpWebRequest)WebRequest.Create(updateFileUrl);
WebResponse webRes = request.GetResponse();
fileLength = webRes.ContentLength; if (File.Exists(tempPath))
File.Delete(tempPath);
FileStream fs = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
Stream srm = webRes.GetResponseStream();
byte[] bufferbyte = new byte[512];
int allByte = (int)fileLength;
int startByte = 0;
while (fileLength > 0)
{
Application.DoEvents();
int downByte = srm.Read(bufferbyte, 0, 512);
if (downByte == 0) { break; };
fs.Write(bufferbyte, 0, downByte);
startByte += downByte;
allByte -= downByte; float part = (float)startByte / 512;
float total = (float)fileLength / 512;
int percent = Convert.ToInt32((part / total) * 100);
}
srm.Close();
fs.Close();
问题:
如果网络正常的话,这个下载就没有问题,但如果下载过程中断网了,我的电脑又没有缓存机制,请问应该怎么处理?
string tempPath = "d:\\" + textBox1.Text.Substring(textBox1.Text.LastIndexOf("/") + 1);
string updateFileUrl = textBox1.Text;
long fileLength = 0;
request = (HttpWebRequest)WebRequest.Create(updateFileUrl);
WebResponse webRes = request.GetResponse();
fileLength = webRes.ContentLength; if (File.Exists(tempPath))
File.Delete(tempPath);
FileStream fs = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
Stream srm = webRes.GetResponseStream();
byte[] bufferbyte = new byte[512];
int allByte = (int)fileLength;
int startByte = 0;
while (fileLength > 0)
{
Application.DoEvents();
int downByte = srm.Read(bufferbyte, 0, 512);
if (downByte == 0) { break; };
fs.Write(bufferbyte, 0, downByte);
startByte += downByte;
allByte -= downByte; float part = (float)startByte / 512;
float total = (float)fileLength / 512;
int percent = Convert.ToInt32((part / total) * 100);
}
srm.Close();
fs.Close();
问题:
如果网络正常的话,这个下载就没有问题,但如果下载过程中断网了,我的电脑又没有缓存机制,请问应该怎么处理?
fs.Write(bufferbyte, 0, downByte);我已经写到文件里了,但如果断网的话,这个文件大小还是0K或者1K