使用WebClient下载遇到的问题

changjiangzhibin 2007-12-19 01:06:48
我在使用WebClient下载服务器(本机)上的文件时:

1)运行调试时,能够下载,可是每次下载的文件都是固定的9KB大小;

2)发布到本机IIS上后不能下载;

不知道为什么?代码如下:请高人指点迷津,不胜感激!

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Threading;
using System.Data.SqlClient;
using System.IO;
using System.Net;

public partial class Default2 : System.Web.UI.Page
{
private WebClient client = new WebClient();
private string URLAddress = string.Empty;
private string fileName = string.Empty;

#region 窗体加载事件
protected void Page_Load(object sender, EventArgs e)
{
this.Title = "测试网页";
Securities security = new Securities();
if (!security.HasLogined())
{
Response.Write("<script>alert('请先登陆!')</script>");
Server.Transfer("Default.aspx");
}
string role = Session["role"].ToString();
if (!role.Equals("employee"))
{
Response.Write("<script>alert('很抱歉,您的权限不够!')</script>");
Server.Transfer("Default.aspx");
}
if (!Page.IsPostBack)
{
DownFileToDirectory();
}
}
#endregion

#region 将选定的种子文件下载到指定目录下
private void DownFileToDirectory()
{
if (Request["key"] != null && !Request["key"].Equals(string.Empty))
{
try
{
int fid = Convert.ToInt32(Request["key"]); //文件的编号,从库中取,服务端有此资源
string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
string sql = "select FileName from fileTable where fileId=" + fid + "";
SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows.Count > 0)
{
URLAddress = "http://192.168.1.210/Test/DownloadList.aspx";
fileName = dt.Rows[0]["FileName"].ToString();
StartDownload();
}
}
catch
{
Response.Redirect("Download.aspx");
}
}
Response.Redirect("Download.aspx");
}
#endregion

#region 下载某网页的文件
private void DownloadFileByUrl()
{
string Dir = @"C:\Program Files\myDirectory\fileByDownload";
if (!Directory.Exists(Dir))
{
Directory.CreateDirectory(Dir);
}
string savePath = Dir + "\\" + fileName;
if (File.Exists(savePath))
{
return;
}

try
{
WebRequest myre = WebRequest.Create(URLAddress);
}
catch (WebException exp)
{
string e = exp.Message;
}

try
{
client.Credentials = CredentialCache.DefaultCredentials;
client.DownloadFile(URLAddress, savePath);
}
catch (WebException exp)
{
string e = exp.Message;
}
finally
{
Thread cur = Thread.CurrentThread;
if (cur.Name.Equals("autoDown"))
{
cur.Abort();
}
}
}
#endregion

#region 启用线程,下载文件
private void StartDownload()
{
Thread th = new Thread(new ThreadStart(DownloadFileByUrl));
th.Name = "autoDown";
th.Start();
}
#endregion
}
...全文
269 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
changjiangzhibin 2007-12-20
  • 打赏
  • 举报
回复
衷心的感谢各位的回复,如2楼、8楼所言非常准确命中问题,谢谢9楼费心贴出代码,
开发人员喜欢探究原理,更喜欢看代码,当然越经典越好。
原因有二:
1、服务器权限不够,加个匿名用户即可解决问题;
2、URL路径未写完整,只找到网页文件,后面还要加上欲下载的资源(可在代码中动态加);
OK,问题初步解决,100分散完,结贴,再次感谢诸位!!!!
Thanks for helping me.
cuike519 2007-12-19
  • 打赏
  • 举报
回复
==〉其实并没有下载服务器上的资源文件,这是为何?
检查URLAddress是不是你要下载的资源?还是一个页面?
MisterDotNet 2007-12-19
  • 打赏
  • 举报
回复
static public bool ResponseFile(HttpRequest _Request,HttpResponse _Response,string _fileName,string _fullPath, long _speed)
{
try
{
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;

int pack = 10240; //10K bytes
//int sleep = 200; //每秒5次 即5*10K bytes每秒
int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = 206;
string[] range = _Request.Headers["Range"].Split(new char[] {'=', '-'});
startBytes = Convert.ToInt64(range[1]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
}
_Response.AddHeader("Connection", "Keep-Alive");
_Response.ContentType = "application/octet-stream";
_Response.AddHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(_fileName,System.Text.Encoding.UTF8) );

br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int) Math.Floor((fileLength - startBytes) / pack) + 1;

for (int i = 0; i < maxCount; i++)
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(pack));
Thread.Sleep(sleep);
}
else
{
i=maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return false;
}
return true;
}


下载文件代码
cuike519 2007-12-19
  • 打赏
  • 举报
回复
1、查看一下下载下来的文件内容是什么?
2、部署到IIS上面后需要设置ASPNET这个用户的权限可以写你要指定的目录。
3、过程中是否有异常?最好能写一下日志,这样能够比较清楚的了解运行时的情况。
4、看看IIS的日志中是否有不正常的地方。
jinjazz 2007-12-19
  • 打赏
  • 举报
回复
你先试试 相同的地址用ie能不能下,应该不是webclient的问题
changjiangzhibin 2007-12-19
  • 打赏
  • 举报
回复
谢谢各位的回复,我下的固定9K似乎是由于下载的是HTML网页文件,
其实并没有下载服务器上的资源文件,这是为何?解决问题立即散分!!
7仔 2007-12-19
  • 打赏
  • 举报
回复
C:\Program Files\myDirectory\fileByDownload
对这个文件夹要给asp.net用户读写的权限
yjwang0621 2007-12-19
  • 打赏
  • 举报
回复
up,study.
wangdetian168 2007-12-19
  • 打赏
  • 举报
回复
大正他爹 2007-12-19
  • 打赏
  • 举报
回复
IIS是否给了权限。
kbryant 2007-12-19
  • 打赏
  • 举报
回复
友情up一下。。。
【资源说明】 1、该资源包括项目的全部源码,下载可以直接使用! 2、本项目适合作为计算机、数学、电子信息等专业的课程设计、期末大作业和毕设项目,作为参考资料学习借鉴。 3、本资源作为“参考资料”如果需要实现其他功能,需要能看懂代码,并且热爱钻研,自行调试。 基于OpenTCS二次开发的 AGV 调度系统源码+项目说明(支持Modbus协议 可与VREP联动仿真车辆 目前支持Modbus, Http, VREP, TCP, Serial协议).zip #### 介绍 开源的交通控制系统,可用于AGV的交通管制系统 #### 使用方式 详情访问 [OpenTCS Page](https://touchmii.github.io/OpenTCS-4) 推荐使用IDEA,打开此项目后等待gradle加载完毕 ![](https://raw.githubusercontent.com/touchmii/uPic/master/imgSnipaste_2020-10-24_17-12-31.png) 根据上图箭头指示运行Kernel和PlantView,如果是调试的话就选择Debug ![](https://raw.githubusercontent.com/touchmii/uPic/master/imgSnipaste_2020-10-24_17-16-28.png) 如要打包程序可选择上图Task里的installDist或Zip,可生成独立运行的程序,如需在其它电脑运行此程序需安装java 8版本的JDK或JRE ####WebClient启动 在gradle里面找到openTCS-WebClient->gretty->jettyRunWar,右键选择运行即可,在浏览器里面打开http://localhost:8090/Demo ![](https://raw.githubusercontent.com/touchmii/uPic/master/img20201107174504.png)) #### 修改部分 添加Modbus驱动 路径发送改为整段路径发送,路径格式为x,y坐标点 长路路径运行时遇到通讯中断无法按照顺序报告走完的点,需修改DefaultVehicleController内命令执行完毕的判断规则 ![](https://raw.githubusercontent.com/touchmii/uPic/master/imgSnipaste_2020-09-21_17-49-50.png) #### 新增Maven支持 ......

62,072

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

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