简体   繁体   English

使用 StreamWriter 在文件中写入 Unicode 字符串不起作用

[英]Write Unicode String In a File Using StreamWriter doesn't Work

I have this code:我有这个代码:

string s = "آ";
StreamWriter writer = new StreamWriter("a.txt", false, Encoding.UTF8);
writer.WriteLine(s);

but when I run it I can't see any "آ" in a.txt!!但是当我运行它时,我在 a.txt 中看不到任何“آ”!! There isn't any string in a.txt! a.txt 中没有任何字符串! It is Empty!它是空的! What is problem!?!什么问题!?! Can anyone help me???谁能帮我???

You never Close() the StreamWriter .你永远不会Close() StreamWriter

If you call writer.Close() when you finish writing, you will see the character.如果你在写完之后调用writer.Close() ,你会看到这个字符。

But, since it implements IDisposable you should wrap the creation of the StreamWriter in a using statement:但是,由于它实现了IDisposable您应该将StreamWriter的创建包装在using语句中:

using(StreamWriter writer = new StreamWriter("a.txt", false, Encoding.UTF8))
{
   writer.WriteLine(s);
}

This will close the stream for you.这将为您关闭流。

By the looks of it you're not Flush() ing or Close() ing the StreamWriter before you end your application.从表面StreamWriter在结束应用程序之前,您不是Flush() ing 或Close() StreamWriter StreamWriter uses a buffer internally which needs to be flushed before you close your application or the StreamWriter goes out of scope otherwise the data you wrote to it will not be written to disc. StreamWriter在内部使用缓冲区,在关闭应用程序之前需要刷新该缓冲区,否则StreamWriter超出范围,否则您写入的数据将不会写入磁盘。

You can call Close() once you're done - although instead I would suggest using a using statement instead to also assure that your StreamWriter gets properly disposed.完成后您可以调用Close() - 尽管相反,我建议使用using语句来确保您的StreamWriter得到正确处理。

string s = "آ";

using (StreamWriter writer = new StreamWriter("a.txt", false, Encoding.UTF8))
{
    writer.WriteLine(s);
}

Try using File.WriteAllText("a.txt", s, Encoding.UTF8);尝试使用File.WriteAllText("a.txt", s, Encoding.UTF8); . .

Follow, complete function for export a listview to excel with correct special characteres:按照完整的功能将列表视图导出到带有正确特殊字符的excel:

private void Exportar()
    {
        Encoding encoding = Encoding.UTF8;

        saveFileDialog1.Filter = "Arquivo Excel (*.xls)|*.xls";
        saveFileDialog1.FileName = "logs";
        saveFileDialog1.Title = "Exportar para Excel";
        StringBuilder sb = new StringBuilder();
        foreach (ColumnHeader ch in lstPesquisa.Columns)
        {
            sb.Append(ch.Text + "\t");
        }
        sb.AppendLine();
        foreach (ListViewItem lvi in lstPesquisa.Items)
        {
            foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
            {
                if (lvs.Text.Trim() == string.Empty)
                {
                    sb.Append(" ");
                }
                else
                {
                    string ITEM = Regex.Replace(lvs.Text, @"\t|\n|\r", "");//remover novas linhas
                    sb.Append(ITEM + "\t");
                }
            }
            sb.AppendLine();
        }
        DialogResult dr = saveFileDialog1.ShowDialog();
        if (dr == DialogResult.OK)
        {
            StreamWriter sw = new StreamWriter(saveFileDialog1.FileName, false, Encoding.UTF32);
            sw.Write(sb.ToString());
            sw.Close();
        }
    }

If you want to read a file from somewhere that contains these Unicode characters then you do some modifications and write back to the file, the problem arises.如果你想从某个地方读取一个包含这些 Unicode 字符的文件,然后你做一些修改并写回文件,问题就会出现。 I was stuck with the same problem.我被同样的问题困住了。 Here is the solution that worked for me这是对我有用的解决方案

Reading data from a file that contains Unicode characters从包含 Unicode 字符的文件中读取数据

List<string>fileData= File.ReadAllLines("URPath",Encoding.Default).ToList());
//Any modifications
File.WriteAllLines("URPath", hstFileData,Encoding.Default);

I know this is not pretty but it worked.我知道这并不漂亮,但它奏效了。 hope this helps!希望这可以帮助!

Few tips:小贴士:

  • do you see any character in the file written in place of one you expect?你看到文件中的任何字符代替了你期望的字符吗? If not you're not flushing and closing the stream如果不是,您不会刷新和关闭流
  • StreamWriter should be able to write unicode without you having to choose encoding, but you could try to use UTF32 encoding. StreamWriter 应该能够编写 unicode,而不必选择编码,但您可以尝试使用 UTF32 编码。

Check How to: Write Text to a File检查如何:将文本写入文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM