关于 WebClient.DownloadFile 下载网络文件

blueicexx 2008-07-21 03:51:36
开发东东为web中的一个打印插件,但有在加载一个图片的时候下载后不报错,但看硬盘中却是空文件夹,以下是代码



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();

}



不知道为什么不能将网络文件下载保存到本地...
...全文
141 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
blueicexx 2008-07-21
  • 打赏
  • 举报
回复
查出来了,是本地路径错了..郁闷

谢谢
hongqi162 2008-07-21
  • 打赏
  • 举报
回复
你得本地路径应该有问题
hongqi162 2008-07-21
  • 打赏
  • 举报
回复

以前用过的,肯定没有问题

/**//// <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;
}

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧