如何在文件内容中编码字符串?

时间:2014-06-27 12:19:54

标签: c# .net winforms

这是我之前在form1构造函数中所做的:

client.Encoding = System.Text.Encoding.GetEncoding(1255);
page = client.DownloadString("http://rotter.net/scoopscache.html");

client = WebClient变量 page =字符串变量

但是我改变了它,我正在使用form1构造函数:

page = OffLineDownload.offlineHtmlFile1();

现在页面具有与以前相同的内容,但不下载它。 如何将编码设置为1255,因为页面中的某些内容是希伯来语?

我现在尝试了这个:

page = Encoding.GetEncoding(1255).ToString();
page = OffLineDownload.offlineHtmlFile1();

但它不起作用我之后收到错误,因为内容不是希伯来语,但有些符号和字符更像是gibrish。

离线课程:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;

namespace ScrollLabelTest
{
    class OffLineDownload
    {
        static string offLineHtmlBeforeChanged;
        static string OffLineHtmlAfterChanged;

        public static string offlineHtmlFile1()
        {
            offLineHtmlBeforeChanged = File.ReadAllText(@"C:\Temp\news\news1.htm");
            return offLineHtmlBeforeChanged;
        }

        public static string offlineHtmlFile2()
        {
            OffLineHtmlAfterChanged = File.ReadAllText(@"C:\Temp\news\news2.htm");
            return OffLineHtmlAfterChanged;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

来自System.Net.WebClient.DownloadString

byte[] bytes = this.DownloadDataInternal(address, out request);
string @string = this.GuessDownloadEncoding(request).GetString(bytes);

相当于

byte[] bytes = File.ReadAllBytes(filename);
string @string = Encoding.GetEncoding(1255).GetString(bytes);

虽然汉斯指出,但一次性完成这项工作会更好

string @string = File.ReadAllText(filename, Encoding.GetEncoding(1255));