为什么会产生异常????

天外怪魔 2003-06-30 06:58:29
代码如下:(用来保存网页)
执行HttpWebResponse myResponse=
(HttpWebResponse)myRequest.GetResponse();
时会产生异常,为什么?
private void btnDown_Click(object sender, System.EventArgs e)
{
// 构造Web请求
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create(txtURL.Text);
// 发送请求获得响应
HttpWebResponse myResponse=
(HttpWebResponse)myRequest.GetResponse();
// 使用到的读写流
Stream myStream=null;
FileStream myfileStream=null;

try
{
// 获得流
myStream=myResponse.GetResponseStream();
// 获得文件长度
long fileSizeInBytes=myResponse.ContentLength;
// 创建文件流对象
myfileStream=new
FileStream(txtLocalFile.Text,FileMode.OpenOrCreate,FileAccess.Write);
// 读取数据缓冲长度和缓冲区
int myLength=1024;
byte[] mybuffer=new byte[1025];
int bytesread=0;
// 从网络中读取数据
while((bytesread=myStream.Read(mybuffer,0,bytesread))>0)
{
// 把数据写入文件
myfileStream.Write(mybuffer,0,bytesread);
}
}
catch(Exception xe)
{

}
finally
{
// 关闭流
if(myStream!=null)
myStream.Close() ;
if(myfileStream!=null)
myfileStream.Close();
}
}
...全文
110 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
天外怪魔 2003-07-01
  • 打赏
  • 举报
回复
是这样的,我用的是XP Professional 版本,在IE的URL中输入"http://www.csdn.net"都是正常的。IE的网页保存功能也正常。
lbx1979 2003-07-01
  • 打赏
  • 举报
回复
其实是没有连接上服务器的问题啊
不是程序问题吧
xixigongzhu 2003-07-01
  • 打赏
  • 举报
回复
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.csdn.net");
StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream());
Console.WriteLine(sr.ReadToEnd());
sr.Close();

在我的机器上完全没错呀。那可能是你的网络的问题拉
timmy3310 2003-07-01
  • 打赏
  • 举报
回复
你的局域网内是不是有防火墙?
如果是,需要设置WebRequest的Proxy属性,指定防火墙的地址和用户名密码
xixigongzhu 2003-07-01
  • 打赏
  • 举报
回复
你在地址栏输入txtURL.Text的值,看看能不能访问。
saucer 2003-07-01
  • 打赏
  • 举报
回复
it works for me, by the way, this line is wrong:

while((bytesread=myStream.Read(mybuffer,0,bytesread))>0)

===>

while((bytesread=myStream.Read(mybuffer,0,myLength))>0)


since bytesread starts as 0
天外怪魔 2003-07-01
  • 打赏
  • 举报
回复
补充一下:发生异常时,txtURL.Text的值为"http://www.csdn.net"
天外怪魔 2003-07-01
  • 打赏
  • 举报
回复
错误提示是:
未处理的“System.Net.WebException”类型的异常出现在 system.dll 中

其他信息:基础连接已经关闭:无法连接到远程服务器。

请各位大侠再帮帮忙:)
lovered 2003-06-30
  • 打赏
  • 举报
回复
[v]
xixigongzhu 2003-06-30
  • 打赏
  • 举报
回复
是什么异常?InvalidOperationException?ProtocolViolationException?WebException?异常信息是什么?
lbx1979 2003-06-30
  • 打赏
  • 举报
回复
错误提示是什么?
saucer 2003-06-30
  • 打赏
  • 举报
回复
可能出的错多了,看看是什么错?

catch(Exception xe)
{
Response.Write(xe.Message);
}

110,538

社区成员

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

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

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