【问题标题】:Encoding.ASCII.GetString returning blank value (Only in windows Application)Encoding.ASCII.GetString 返回空白值(仅在 windows 应用程序中)
【发布时间】:2012-12-17 06:51:42
【问题描述】:

我正在尝试使用 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 ...在上面的 cmets 中。 (那么设备一定是在发送损坏的数据?不,因为如果上面的代码在控制台应用程序中运行,它会完美运行并输出正确的字符串)

任何帮助将不胜感激。

【问题讨论】:

  • 数据是否在任何时候都包含 0 字节?
  • 在 Encoding.ASCII.GetString 有效而无效时,hex_string 的外观如何?
  • 为什么不 Encoding.ASCII.GetString(bytes); ???
  • 试图重现该问题,但我无法显示 MessageBox,这是有道理的,因为您没有从主 UI 线程 (stackoverflow.com/questions/559252/…) 调用 MessageBox.Show。此外,MessageBox.Show(ascii_string.Length) 不会编译(方法需要一个字符串)。你确定你发布了你正在测试的代码吗?
  • 它看起来总是有效的。但是 MessageBox 调用 windows API,它将 0 视为行尾,因此该字符串对于 windows API 来说似乎是空的。

标签: c# windows ascii encode udpclient


【解决方案1】:

如 cmets 中所述,字符串以 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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 2012-12-06
    • 1970-01-01
    相关资源
    最近更新 更多