【问题标题】:C# how to get proper string from GetString()C# 如何从 GetString() 获取正确的字符串
【发布时间】:2018-02-27 18:41:07
【问题描述】:

我用:

propItem.Value = System.Text.Encoding.UTF8.GetBytes(textBox1.Text + "\0");

其中 textBox1.Text 包含“MMM”,设置值并将其保存在文件中(propItem.Value 为 byte[]),但是当我尝试读取文件时,我使用:

string myString = System.Text.Encoding.UTF8.GetString(propItem.Value);

并得到:“M\0M\0M\0\0\0”。任何人都可以建议如何在没有'\0'的情况下获得正确的字符串。我在这里看到了有关类似问题的所有答案,但没有一个答案对我有用。

加载文件:

Image img0 = null;
string sourceFile;

private void btnLoad_Click(object sender, EventArgs e)
    {
        using (var selectFileDialog = new OpenFileDialog())
        {
            if (selectFileDialog.ShowDialog() == DialogResult.OK)
            {
                sourceFile = selectFileDialog.FileName;

                img0 = Image.FromFile(sourceFile);

                PropertyItem[] propItems = img0.PropertyItems;

                textBox1.Text = "Nothing in the file."; 
                foreach (PropertyItem propItem in propItems)
                {
                    if (propItem.Id == 0x9286)
                    {
                        string myString = System.Text.Encoding.UTF8.GetString(propItem.Value); 
                        textBox1.Text = myString ;
                    } 
                }
            }
        }
    }

【问题讨论】:

  • 请分享您用于从文件中读取字节的代码
  • 如果textBox1 是WinForm 或WPF TextBox,那么textBox1.TextSystem.Text.Encoding.Unicode 不是 UTF8
  • 这是 WinForm 应用程序,但我正在查看 Watch 中的 myString 值。
  • 太棒了!!!! :-)。 Unicode 是 Asnwer。非常感谢。
  • @DourHighArch 实际上,不是。从控件检索的字符串将是一个普通的 .Net 字符串对象,没有任何与用户相关的编码概念。编码仅在 转换为字节之后才相关。对我来说,转换为字节看起来还不错……一定是图像保存做了更多的转换。

标签: c# encoding utf-8 byte getstring


【解决方案1】:

应该是:

string myString = System.Text.Encoding.Unicode.GetString(propItem.Value);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    相关资源
    最近更新 更多