110,538
社区成员
发帖
与我相关
我的任务
分享
bool Result = true;
WebClient client = new WebClient();
try
{
client.DownloadFile(HttpPath, "./" + fileName);//应该这样就可以下载到本地的,但硬盘里却没文件
}
catch
{
Result = false;//返回值
}
//如果下载失败,换一种方式下载
if (!System.IO.File.Exists("./" + fileName))
{
//换一种方式下载
Stream str = client.OpenRead(HttpPath);
StreamReader reader = new StreamReader(str);
byte[] mbyte = new byte[10000000];
int allmybyte = mbyte.Length;
int startmbyte = 0;
while (allmybyte > 0)
{
int m = str.Read(mbyte, startmbyte, allmybyte);
if (m == 0)
break;
startmbyte += m;
allmybyte -= m;
}
FileStream fstr = new FileStream(DestPath, FileMode.Create, FileAccess.Write);
fstr.Flush();
str.Close();
fstr.Close();
}
以前用过的,肯定没有问题
/**//// <summary>
/// 下载服务器文件至客户端
/// </summary>
/// <param name="uri">被下载的文件地址</param>
/// <param name="savePath">另存放的目录</param>
public static bool Download(string uri, string savePath)
{
/**url 文件名解析
string fileName; //被下载的文件名
if (uri.IndexOf(@"\") > -1)
{
fileName = uri.Substring(uri.LastIndexOf(@"\") + 1);
}
else
{
fileName = uri.Substring(uri.LastIndexOf("/") + 1);
}
if (!savePath.EndsWith("/") && !savePath.EndsWith(@"\"))
{
savePath = savePath + "/";
}
savePath += fileName; //另存为的绝对路径+文件名
* */
WebClient client = new WebClient();
try
{
client.DownloadFile(uri, savePath);
}
catch
{
return false;
}
return true;
}