【发布时间】:2011-01-23 00:16:34
【问题描述】:
我正在尝试使用本地 c# 应用程序将一些图像从网站拉到本地计算机上的文件中。我正在使用下面列出的代码。我尝试了 ASCII 编码和 UTF8 编码,但最终文件不正确。有谁看到我做错了什么?当我将地址放入浏览器时,该网址是有效且正确的,并且可以很好地显示图像。
private void button1_Click(object sender, EventArgs e)
{
HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create("http://www.productimageswebsite.com/images/stock_jpgs/34891.jpg");
// returned values are returned as a stream, then read into a string
String lsResponse = string.Empty;
HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse();
using (StreamReader lxResponseStream = new StreamReader(lxResponse.GetResponseStream()))
{
lsResponse = lxResponseStream.ReadToEnd();
lxResponseStream.Close();
}
byte[] lnByte = System.Text.UTF8Encoding.UTF8.GetBytes(lsResponse);
System.IO.FileStream lxFS = new FileStream("34891.jpg", FileMode.Create);
lxFS.Write(lnByte, 0, lnByte.Length);
lxFS.Close();
MessageBox.Show("done");
}
【问题讨论】:
-
顺便说一句,您的 HttpWebResponse 和 FileStream 对象需要使用块,因为它们实现了 IDisposable。另外,为什么要初始化 lsResponse,因为它总是会被设置(否则会抛出异常)。最后,我建议你停止使用匈牙利符号(lxFS),你不需要前缀就可以知道每个对象的类型。只需将鼠标悬停在它上面。
标签: c# image file httpwebrequest