使用WebClient下载遇到的问题
我在使用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
}