Encoding.ASCII.GetString返回空值(仅在windows应用程序中)

本文关键字:windows 应用程序 仅在 ASCII GetString 返回 空值 Encoding | 更新日期: 2023-09-27 17:50:32

我试图用Visual Studio 2012创建一个windows应用程序,但奇怪的事情似乎正在发生…当我在控制台应用程序中运行完全相同的代码时,它工作得很好,但似乎我无法在windows应用程序项目的线程中运行以下代码:

private void VisualUDPListener_Load(object sender, EventArgs e)
    {
        //System.Windows.Forms.Form.CheckForIllegalCrossThreadCalls = false;
        new Thread(delegate()
        {
            StartListener();
        }).Start();
    }
    private void StartListener()
    {
        UdpClient listener = new UdpClient(listenPort);
        IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
        try
        {
            while (true)
            {
                //log text box
                Log.AppendText("Listening 'n");
                byte[] bytes = listener.Receive(ref groupEP);
                string hex_string = BitConverter.ToString(bytes);//this works and returns the correct hex data
                string ascii_string = Encoding.ASCII.GetString(bytes, 0, bytes.Length);//blank???????????
                MessageBox.Show(ascii_string.Length.toString());//outputs 131 which is correct
                MessageBox.Show(ascii_string);// shows a blank message box
                Log.AppendText("--" + ascii_string + hex_string +" 'n");//only outputs --
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        finally
        {
            listener.Close();
        }
    }

我的目标是。net Framework 4.5…如果我从测试java应用程序发送UDP数据,它会收到数据,但如果我通过移动设备发送完全相同的数据,代码的目的是它会像上面的评论一样空。(那么设备一定是在发送损坏的数据?不,因为如果上面的代码在控制台应用程序中运行,它会完美运行并输出正确的字符串)

Encoding.ASCII.GetString返回空值(仅在windows应用程序中)

如注释中所述,字符串以0字节开始(00-04-02-00-20)。它被正确地转换为c#字符串。MessageBox.Show调用windows api函数MessageBox。Windows API使用以零结尾的字符串,所以这个特定的字符串在WinAPI看来是空的,因为第一个字节是零。使用以零结尾的字符串的api不能逐字记录/显示此字符串。

您需要用其他东西替换0,如ascii_string.Replace((char)0, (char)1)或使用不将零视为特殊字符的api。