如何从URL中获取数据并将其保存到C#.NET中的二进制文件中,而不会出现编码问题?

时间:2009-06-14 09:18:06

标签: c# .net http encoding binary

在C#.NET中,我想从URL获取数据并将其保存为二进制文件。

使用HttpWebRequest / Streamreader读取字符串并使用StreamWriter保存可以正常使用ASCII,但非ASCII字符会受到损坏,因为系统认为它必须担心编码,编码为Unicode或来自或等等。

从URL获取数据并将其保存到文件二进制文件的最简单方法是什么?

// This code works, but for ASCII only
String url = "url...";
HttpWebRequest  request  = (HttpWebRequest)
WebRequest.Create(url);

// execute the request
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();

// we will read data via the response stream
Stream ReceiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader( ReceiveStream );
string contents = readStream.ReadToEnd();

string filename = @"...";

// create a writer and open the file
TextWriter tw = new StreamWriter(filename);
tw.Write(contents.Substring(5));
tw.Close();

3 个答案:

答案 0 :(得分:55)

极简主义回答:

using (WebClient client = new WebClient()) {
    client.DownloadFile(url, filePath);
}

或者在PowerShell中(匿名编辑中建议):

[System.Net.WebClient]::WebClient
$client = New-Object System.Net.WebClient
$client.DownloadFile($URL, $Filename)

答案 1 :(得分:14)

只是不要使用任何StreamReader或TextWriter。使用原始FileStream保存到文件中。

String url = ...;
HttpWebRequest  request  = (HttpWebRequest) WebRequest.Create(url);

// execute the request
HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// we will read data via the response stream
Stream ReceiveStream = response.GetResponseStream();

string filename = ...;

byte[] buffer = new byte[1024];
FileStream outFile = new FileStream(filename, FileMode.Create);

int bytesRead;
while((bytesRead = ReceiveStream.Read(buffer, 0, buffer.Length)) != 0)
    outFile.Write(buffer, 0, bytesRead);

// Or using statement instead
outFile.Close()

答案 2 :(得分:0)

这就是我使用的:

sUrl = "http://your.com/xml.file.xml";
rssReader = new XmlTextReader(sUrl.ToString());
rssDoc = new XmlDocument();

WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sUrl);

Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream, Encoding.UTF8);
WebResponse wr = wrGETURL.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
XmlDocument content2 = new XmlDocument();

content2.LoadXml(content);
content2.Save("direct.xml");