如何在c#中编码tcpclient流?

时间:2012-07-02 09:03:01

标签: c# encoding tcpclient pop3

我的pop3客户端有问题。 我无法在utf-8或iso 8859-1中编码从tcpclient流中检索的电子邮件。 这是代码:

TcpClient tcpClient = new TcpClient();
txtLog.Text = "Dico:\r\nConnect me to " + txtServer.Text + ":" + txtPort.Text + "\r\n\r\n";
tcpClient.Connect(txtServer.Text, Convert.ToInt32(txtPort.Text));
NetworkStream netStream = tcpClient.GetStream();
System.Text.Encoding iso_8859_1 = System.Text.Encoding.GetEncoding("iso-8859-1");
System.IO.StreamReader strReader = new System.IO.StreamReader(netStream, iso_8859_1);

System.Text.Encoding utf_8 = System.Text.Encoding.UTF8;


if (tcpClient.Connected)
{
    txtLog.Text = "Il server risponde:\r\n" + strReader.ReadLine() + "\r\n\r\n";
    byte[] WriteBuffer = new byte[100990024];
    ASCIIEncoding enc = new System.Text.ASCIIEncoding();

    WriteBuffer = enc.GetBytes("USER " + txtUser.Text + "\r\n");
    txtLog.Text = "Dico:\r\nHere's the username: " + txtUser.Text + "\r\n\r\n";
    netStream.Write(WriteBuffer, 0, WriteBuffer.Length);
    txtLog.Text = "Il server risponde\r\n" + strReader.ReadLine() + "\r\n\r\n";
    WriteBuffer = enc.GetBytes("PASS " + txtPass.Text + "\r\n");
    txtLog.Text = "Dico:\r\nHere's the password: " + txtPass.Text + "\r\n\r\n";
    netStream.Write(WriteBuffer, 0, WriteBuffer.Length);
    txtLog.Text = "Il server risponde\r\n" + strReader.ReadLine() + "\r\n\r\n";

    WriteBuffer = enc.GetBytes("RETR " + messaggio.Text + "\r\n");
    txtLog.Text = "Messaggio: " + messaggio.Text + "\r\n\r\n";
    string message;
    netStream.Write(WriteBuffer, 0, WriteBuffer.Length);
    while (true)
    {
        message = strReader.ReadLine();
        if (message == ".")
        {
            if (message == "/n") break;
            break;
        }
        else
        {
            txtLog.Text += message + "\r\n\r\n";
            continue;
        }
    }

我总是得到这样的东西“questa_ = E8_una_prova_ = F2_ = EC _?=”。 怎么了? 谢谢。

1 个答案:

答案 0 :(得分:0)

您正在查看传输编码,该编码用于传输文本编码产生的字节。

虽然文本可能使用UTF-8或任何其他字符集进行编码,但传输编码通常为base 64quoted-printable。字符串"questa_=E8_una_prova_=F2_=EC_?="看起来像后者。

查看here如何将quoted-printable解码为字符串,并查看here以了解.NET中现有的POP3客户端实现。