【问题标题】:C# StreamWriter outputting in JapaneseC# StreamWriter 以日语输出
【发布时间】:2014-09-22 12:54:00
【问题描述】:

出于某种奇怪的原因,我正在从 .txt(记事本)文件中读取数据,并且我只想删除前 5 位数字。程序运行后,我的输出文件将以我认为是日文的形式打印。我将发布一些代码,以及下面的示例输入和输出。在追查为什么会发生这种情况时,我们将不胜感激。谢谢。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace BasicFileStripper
{
class Program
{
    static void Main(string[] args)
    {
        //var encoding = new ASCIIEncoding();
        StreamWriter write = new StreamWriter(@"C:\Users\Josh\Desktop\MillerEpicOutputs\ClientIds.txt");
        StreamReader read = new StreamReader(@"C:\Users\Josh\Desktop\MillerEpicOutputs\j.txt");//, encoding);
        string line;
        int count = 0;
        write.Write("{");
        while ((line = read.ReadLine()) != null)
        {
            count++;
            string copy = line.Substring(0, 5);
            write.Write(copy + ",");
            Console.WriteLine(line);
        }
        write.WriteLine("};");
        write.WriteLine("Count: " + count);
        write.Close();
    }
}
}

示例输入:

68669 - (DO NOT USE)
68363 - 100 Men of Blue Hills
68364 - 10484 Marty LLC
68365 - 21st Century Therapy
69006 - 21st Century Therapy PC
69007 - 31 Dodge Partnership
69008 - 34 Merriam, LLC
69009 - 3525 Sage Council of Co-Owners

样本输出: 㙻㘸㤶㘬㌸㌶㘬㌸㐶㘬㌸㔶㘬〹㘰㘬〹㜰㘬〹㠰㘬〹㤰㘬〹〱㜬㄰㐹㜬

【问题讨论】:

  • 您是否尝试过在用于查看输出文件的文本编辑器上切换编码以查看是否是问题所在?
  • 我使用的是记事本,我认为它根本没有编码数据?

标签: c# streamwriter


【解决方案1】:

那些可能是指定文件是 unicode 而不是 ansi 的字符。

您是在文本编辑器中将文件作为 ANSI 文件打开吗?如果是这样,这就是您看到 > 字符的原因。尝试以 unicode 格式打开它,或者将您的编码设置为非 unicode。

From here

【讨论】:

    【解决方案2】:

    我假设您正在尝试在记事本中读取输出(请参阅 (this Wikipedia article)。将 StreamWriter(String, Boolean, Encoding) constructorEncoding.UTF8 一起使用,这将导致将 BOM 写入输出文件,从而使记事本读取它正确。如果您不需要在记事本中读取它,请保持原样,并注意任何其他读取它并期望它是 UTF-8 的东西都会正确读取它。

    【讨论】:

    • 这修复了它。非常感谢。
    【解决方案3】:

    保存的文件没有正确的编码。这就是为什么您最终会使用日语字符。如果您不将数据作为文件使用,则没有真正的问题。如果您将其作为文件使用,则需要对其进行正确编码以使其可读。

    【讨论】:

      猜你喜欢
      • 2013-05-07
      • 2016-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      相关资源
      最近更新 更多