从c#中的多种编码读取文件
Read file from multiple encoding in c#
环境:C#、VStudio 2013、4.5 框架、Winforms、nHapi 2.3 dll
我真的需要这方面的帮助。我已经尝试了很多东西,并且和我最好的朋友 google 做了很多研究;-)。但是运气不好。
我正在构建一个 HL7 发送器工具,并且正在从一个文件夹中读取文件。我的文件来自多个来源,我发现它们有不同的编码:我用记事本++打开它们,它们可以是 ainsi、utf8 和 utf8 witout BOM。我的文件还包含特殊字符,如 é、à、ç、ô、.... 但当我用这一行读取文件时,它们总是会添加奇怪的字符:var hl7message = File.ReadAllText(e.Node.Name);
我唯一没有遇到任何问题的情况是源文件使用 BOM 以 UTF8 编码。
有没有办法不管源文件的编码是什么,我总是能以字符串形式读取文件并正确显示特殊字符。
这是我的代码的主要部分:
var hl7message = File.ReadAllText(FileName);
var llphl7message = Convert.ToChar(11).ToString() + newmessage + Convert.ToChar(28).ToString() + Convert.ToChar(13).ToString();
// Get the size of the message that we have to send.
Byte[] bytesSent = Encoding.Default.GetBytes(llphl7message);
Byte[] bytesReceived = new Byte[256];
// Create a socket connection with the specified server and port.
Socket s = ConnectSocket(txtParamServer.Text, Convert.ToInt32(txtParamPort.Text));
// If the socket could not get a connection, then return false.
if (s == null)
{
txtLog.Text = txtLog.Text + "[" + DateTime.Now + "] [ERR] Serveur " + txtParamServer.Text + " sur le port " + txtParamPort.Text + " est non disponible" + "\r\n";
return false;
}
// Send message to the server.
s.Send(bytesSent, bytesSent.Length, 0);
谢谢你的帮助
抱歉英语不好:不是我的主要语言
理查德
试试 StreamReader class。它有一个参数 "detectEncodingFromByteOrderMarks".
string result;
using (System.IO.StreamReader reader = new System.IO.StreamReader("FILENAME", true))
{
result = reader.ReadToEnd();
}
环境:C#、VStudio 2013、4.5 框架、Winforms、nHapi 2.3 dll
我真的需要这方面的帮助。我已经尝试了很多东西,并且和我最好的朋友 google 做了很多研究;-)。但是运气不好。
我正在构建一个 HL7 发送器工具,并且正在从一个文件夹中读取文件。我的文件来自多个来源,我发现它们有不同的编码:我用记事本++打开它们,它们可以是 ainsi、utf8 和 utf8 witout BOM。我的文件还包含特殊字符,如 é、à、ç、ô、.... 但当我用这一行读取文件时,它们总是会添加奇怪的字符:var hl7message = File.ReadAllText(e.Node.Name);
我唯一没有遇到任何问题的情况是源文件使用 BOM 以 UTF8 编码。
有没有办法不管源文件的编码是什么,我总是能以字符串形式读取文件并正确显示特殊字符。
这是我的代码的主要部分:
var hl7message = File.ReadAllText(FileName);
var llphl7message = Convert.ToChar(11).ToString() + newmessage + Convert.ToChar(28).ToString() + Convert.ToChar(13).ToString();
// Get the size of the message that we have to send.
Byte[] bytesSent = Encoding.Default.GetBytes(llphl7message);
Byte[] bytesReceived = new Byte[256];
// Create a socket connection with the specified server and port.
Socket s = ConnectSocket(txtParamServer.Text, Convert.ToInt32(txtParamPort.Text));
// If the socket could not get a connection, then return false.
if (s == null)
{
txtLog.Text = txtLog.Text + "[" + DateTime.Now + "] [ERR] Serveur " + txtParamServer.Text + " sur le port " + txtParamPort.Text + " est non disponible" + "\r\n";
return false;
}
// Send message to the server.
s.Send(bytesSent, bytesSent.Length, 0);
谢谢你的帮助 抱歉英语不好:不是我的主要语言
理查德
试试 StreamReader class。它有一个参数 "detectEncodingFromByteOrderMarks".
string result;
using (System.IO.StreamReader reader = new System.IO.StreamReader("FILENAME", true))
{
result = reader.ReadToEnd();
}