.NET WebClient 抓取文本是否错误?
我以为我已经把这个 unicode 东西搞下来了。然后我意识到我没有正确保存/解析一些文本。
这是文本(抱歉,我不知道它说什么。随机用户写的)
这是简单的测试代码。本质上,我为 utf-8 unicode 编写 BOM 并编写源代码。这不起作用,出于理智原因,我尝试直接保存文件(第二段代码)。两者都在文件中得到了错误的文本,并且使用多个浏览器显示了错误的文本。
为什么以及如何修复它?
注意:通过我的第一个代码,我可以看到 sz 使用 Visual Studio 持有相同的错误文本。
using System;
using System.IO;
using System.Net;
using System.Text;
namespace unicode_stuff
{
class Program
{
static void Main(string[] args)
{
var wc = new WebClient();
var fn = "out.html";
var sw = new StreamWriter(fn, false, Encoding.UTF8);
var sz = wc.DownloadString("http://www.pastie.org/pastes/1703099/text");
sw.WriteLine(sz);
sw.Close();
}
}
}
第二
using System;
using System.IO;
using System.Net;
namespace unicode_stuff
{
class Program
{
static void Main(string[] args)
{
var wc = new WebClient();
var fn = "out.html";
wc.DownloadFile("http://www.pastie.org/pastes/1703099/text", fn);
}
}
}
I thought i had this unicode thing down. Then i realize i wasnt saving/parsing some text correctly.
Heres the text (sorry, i dont know what it says. A random user wrote it)
Here is simple test code. Essentially i write the BOM for utf-8 unicode and write the source. That didnt work and for sanity reasons i tried saving the file directly (second piece of code). Both got the WRONG text in file and using multiple browsers it showed me incorrect text.
Why and how do i fix it?
Note: With my first code i can see sz holding the same incorrect text using visual studios.
using System;
using System.IO;
using System.Net;
using System.Text;
namespace unicode_stuff
{
class Program
{
static void Main(string[] args)
{
var wc = new WebClient();
var fn = "out.html";
var sw = new StreamWriter(fn, false, Encoding.UTF8);
var sz = wc.DownloadString("http://www.pastie.org/pastes/1703099/text");
sw.WriteLine(sz);
sw.Close();
}
}
}
second
using System;
using System.IO;
using System.Net;
namespace unicode_stuff
{
class Program
{
static void Main(string[] args)
{
var wc = new WebClient();
var fn = "out.html";
wc.DownloadFile("http://www.pastie.org/pastes/1703099/text", fn);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
加载前尝试将编码设置为 UTF8:
try setting your encoding to UTF8 before loading: