我在使用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
}
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
}
对这个文件夹要给asp.net用户读写的权限
其实并没有下载服务器上的资源文件,这是为何?解决问题立即散分!!
2、部署到IIS上面后需要设置ASPNET这个用户的权限可以写你要指定的目录。
3、过程中是否有异常?最好能写一下日志,这样能够比较清楚的了解运行时的情况。
4、看看IIS的日志中是否有不正常的地方。
{
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;
}
下载文件代码
检查URLAddress是不是你要下载的资源?还是一个页面?
开发人员喜欢探究原理,更喜欢看代码,当然越经典越好。
原因有二:
1、服务器权限不够,加个匿名用户即可解决问题;
2、URL路径未写完整,只找到网页文件,后面还要加上欲下载的资源(可在代码中动态加);
OK,问题初步解决,100分散完,结贴,再次感谢诸位!!!!
Thanks for helping me.