Converting SQL Server varBinary data into string C#

后端 未结 3 1933
小蘑菇
小蘑菇 2020-12-03 13:42

I need help figuring out how to convert data that comes in from a SQL Server table column that is set as varBinary(max) into a string in or

相关标签:
3条回答
  • 2020-12-03 14:19

    You need to know what encoding was used to create the binary. Then you can use

    System.Text.Encoding.UTF8.GetString(reader[1]);
    

    And change UTF8 for whatever encoding was used.

    0 讨论(0)
  • 2020-12-03 14:26

    The binary data must be encoded text - and you need to know which encoding was used in order to accurately convert it back to text. So for example, you might use:

    byte[] binaryData = reader[1];
    string text = Encoding.UTF8.GetString(binaryData);
    

    or

    byte[] binaryData = reader[1];
    string text = Encoding.Unicode.GetString(binaryData);
    

    or various other options... but you need to know the right encoding. Otherwise it's like trying to load a JPEG file into an image viewer which only reads PNG... but worse, because if you get the wrong encoding it may appear to work for some strings.

    The next thing to work out is why it's being stored as binary in the first place... if it's meant to be text, why isn't it being stored that way.

    0 讨论(0)
  • 2020-12-03 14:43

    It really depends on which encoding was used when you originally converted from string to binary:

     byte[] binaryString = (byte[])reader[1];
    
     // if the original encoding was ASCII
     string x = Encoding.ASCII.GetString(binaryString);
    
     // if the original encoding was UTF-8
     string y = Encoding.UTF8.GetString(binaryString);
    
     // if the original encoding was UTF-16
     string z = Encoding.Unicode.GetString(binaryString);
    
     // etc
    
    0 讨论(0)
提交回复
热议问题