【问题标题】:Special Characters on Windows Phone 8 with StreamReader带有 StreamReader 的 Windows Phone 8 上的特殊字符
【发布时间】:2014-04-03 12:48:07
【问题描述】:

我想用 StreamReader 读取一个 txt 文件,然后把它交给 TextBlock。该代码适用于 Windows Phone 应用程序,使用 C#:

var resource = System.Windows.Application.GetResourceStream(new Uri("File.txt", UriKind.Relative));
StreamReader sreader = new StreamReader(resource.Stream);

while ((line = sreader.ReadLine()) != null)
{
   TextBlock.Text = sreader.ReadLine();
}

这会将文件中的所有文本读取到我的 TextBlock 中,但其中有特殊字符,例如 ä 或 ü 或 ö,它们不会显示在 TextBlock 中。如何在我的 TextBlock 中显示这些字符?

【问题讨论】:

    标签: c# text windows-phone-8 streamreader


    【解决方案1】:

    尝试用encoding 定义StreamReader - 例如UTF8:

    using (StreamReader sreader = new StreamReader(resource.Stream, System.Text.Encoding.UTF8))
    { 
      while ((line = sreader.ReadLine()) != null)
        TextBlock.Text = sreader.ReadLine();
    }
    

    StreamReader 放入using 也很有用,因为它是IDisposable


    如果您需要UTF8或Unicode以外的其他编码,则可以尝试使用this program生成编码。

    this answer 之后,您应该粘贴生成的代码,然后将其用于您的 StreamReader(我没有尝试过):

    Encoding myEncoding = new GeneratedEncoding();
    

    然后:

    using (StreamReader sreader = new StreamReader(resource.Stream, myEncoding))
    

    【讨论】:

    • 感谢您的回答,但是使用 UTF8 编码我也没有像 ä 或 ü 这样的特殊字符。这些是德语字母。
    • @user3493797 你也试过System.Text.Encoding.Unicode吗?
    • @user3493797 在 Silverlight 中只有 UTF-8 和 Unicode,如果您需要更多,您可以在 this program 的帮助下使用您的编码进行类。
    • 当我尝试 Unicode 时,TextBlock 是空的,所以没有显示文本。
    • 如果程序没有帮助 - 你有没有机会将你的 file.txt 放在某个地方(或者可能更好 - 简单的应用程序)?
    猜你喜欢
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 2012-10-06
    • 2018-11-14
    相关资源
    最近更新 更多