-1

I use:

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

where textBox1.Text contains "MMM", to set the Value and save it in a file (propItem.Value is byte[]), but when I try to read the file I use:

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

and get: "M\0M\0M\0\0\0". Could anybody advice how to get the proper string, without '\0'. I have seen all the answers here regarding the similar problems, but none of the answers worked in my case.

Loading the file:

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 ;
                    } 
                }
            }
        }
    }
Joe
  • 118
  • 2
  • 6
  • 1
    Please share code which you're using to read the bytes from file – Serega Feb 27 '18 at 18:43
  • If `textBox1` is a WinForm or WPF `TextBox`, then `textBox1.Text` is `System.Text.Encoding.Unicode` **not** `UTF8`. – Dour High Arch Feb 27 '18 at 18:57
  • This is WinForm app, but I'm checking the myString value in Watch. – Joe Feb 27 '18 at 19:04
  • Great!!!! :-). The Unicode was the the Asnwer. Many Thanks. – Joe Feb 27 '18 at 19:07
  • @DourHighArch Actually, no it isn't. The string retrieved from a control will be a plain .Net string object, without any concept of encoding that is relevant to the user. Encoding is only relevant _after_ conversion to bytes. And that conversion to bytes looks OK to me... must be the image saving doing more conversion. – Nyerguds Mar 20 '18 at 00:00

1 Answers1

0

It should be:

string myString = System.Text.Encoding.Unicode.GetString(propItem.Value);
Joe
  • 118
  • 2
  • 6