[英]How to encode for special character?
I am having an issue with my file output. 我的文件输出有问题。 I need to write to a file the character ý and þ.
我需要将字符ý和write写入文件。 I can do this using Convert.ToChar(0253) & Convert.ToChar(0254).
我可以使用Convert.ToChar(0253)和Convert.ToChar(0254)来做到这一点。 This is an old program that I have rewritten in C# from basic+.
这是我从basic +用C#重写的旧程序。 The old program created a simple text file that if opened in wordpad would render the special characters ý & þ.
旧程序创建了一个简单的文本文件,如果在写字板中打开该文件,则会呈现特殊字符ý&þ。 However, when I create the file and open it in wordpad it renders the characters as ý and þ.
但是,当我创建文件并在写字板中打开文件时,它会将字符呈现为½和¾。 Below is the output file opened in both notepad and wordpad.
下面是在记事本和写字板中打开的输出文件。 How can I output the characters so that they will render as ý and þ in both notepad and wordpad?
如何输出字符,以便它们在记事本和写字板中都呈现为ý和?? I have also inserted my code below.
我也在下面插入了我的代码。 Thanks in advance.
提前致谢。
This renders fine in notepad like so: 这样可以在记事本中很好地呈现:
3/31/2015ý15þ
14182515þ
ENDþ
However, when opening the file in wordpad it renders like this: 但是,在写字板中打开文件时,其呈现方式如下:
3/31/2015ý15þ
14182515þ
ENDþ
textOut.WriteLine(shortDate + Convert.ToChar(0253) + cRenPer + Convert.ToChar(0254));
You should specify either UTF8 or UTF16 encoding when writing the file. 写入文件时,您应该指定UTF8或UTF16编码。 You can do it like this:
您可以这样做:
StreamWriter writer = new StreamWriter(<file path>, false, Encoding.UTF8);
You can set the encoding when you define the streamreader 您可以在定义流阅读器时设置编码
StreamWriter textOut = new StreamWriter(new FileStream((dirPath + batchNum + ".REN"),
FileMode.Create, FileAccess.Write),
Encoding.UTF8);
So, as Thorsten Dittmar had suggested I needed to encode the stream-writer as utf8. 因此,正如Thorsten Dittmar所建议的那样,我需要将流编写器编码为utf8。 This allowed the file to be read by the preexisting application as it should be.
这允许现有应用程序按原样读取文件。 Below is the change to the stream-writer class.
下面是对stream-writer类的更改。
StreamWriter textOut = new StreamWriter((dirPath + batchNum + ".REN"), false, new UTF8Encoding(true));
This is an edit: I ended up modifying the code. 这是一个编辑:我最终修改了代码。 Although the text file ended up being interpreted correctly in word-pad it was still not being read by the legacy application.
尽管文本文件最终在写字板中被正确解释,但旧版应用程序仍未读取该文件。 My modified code is below:
我的修改代码如下:
StreamWriter textOut = new StreamWriter(new FileStream((dirPath + batchNum + ".REN"),
FileMode.Create, FileAccess.Write),
System.Text.UnicodeEncoding.Default);
You could write to file using the following code , note the 2nd encoding parameter. 您可以使用以下代码写入文件,请注意第二个编码参数。 This will effect how the file is encoded , which in turn will effect how will ite will be treated by various text editors.
这将影响文件的编码方式,进而影响各种文本编辑器对待ite的方式。
string fileName = "myFile.txt";
using (TextWriter textOut = new StreamWriter(File.OpenWrite(fileName),System.Text.Encoding.Unicode))
{
textOut.WriteLine(Convert.ToChar(0254));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.