本文介绍了如何在C#中读取SQL的varbinary作为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个Web应用程序,它从SQL中读取varbinary作为代码中的字节数组。基本上它会执行列的ExecuteScalar并将其作为字节数组返回。 我现在正在将该应用程序的迷你版本作为Windows应用程序。为此,我试图跳过数据库连接。我直接从SQL输入varbinary值到RichTextBox并尝试将其作为字节数组读取。但是,我没有得到相同的字节数组。我做错了什么,我该怎么办? 基本上,我手头有varbinary值(例如:B0015379737)。这是我从SQL中获取的varbinary值。现在,我想简单地将此值粘贴到文本框中,并将其作为字节数组读取。基本上源是varbinary。我将输入作为字符串,我希望输出为字节数组,匹配源varbinaryI have an web application which reads varbinary from SQL as a byte array in code. Basically it does a ExecuteScalar of the column and returns it as a byte array.I am now doing a mini version of the application as a Windows application. For this, I am trying to skip the DB connection. I am directly inputting the varbinary value from SQL to a RichTextBox and trying to read it as a byte array. However, I do not get the same byte array. What am I doing wrong and how should I proceed ?Basically, I have in hand the varbinary value (eg: "B0015379737"). This is a varbinary value i have taken from SQL. Now, I want to simply paste this value in a textbox and read it as byte array. Basically the source is varbinary. I am giving input as a string and I want the output as byte array which matches the source varbinary推荐答案byte[] binaryString = (byte[])reader[1];// if the original encoding was ASCIIstring ascii = Encoding.ASCII.GetString(binaryString);// if the original encoding was UTF-8string utf = Encoding.UTF8.GetString(binaryString);// if the original encoding was UTF-16string utfs = Encoding.Unicode.GetString(binaryString);using System.Globalization;using System.Text;public static byte[] ByteArrayFromHexaString(string hexa) { int length = hexa.Length; List<byte> result = new List<byte>(); // Fetch whether there are an odd or even number of chars bool isOdd = ((length & 1) == 1); if (isOdd) { result.Add(byte.Parse(hexa[0], NumberStyles.HexNumber)); } string s; for (int i = (isOdd) ? 1 : 0; i < length; i += 2) { s = hexa.SubString(i, 2); result.Add(byte.Parse(s, NumberStyles.HexNumber)); } return result.ToArray();}public static string StringFromByteArray(byte[] bytes, Encoding encoding) { return encoding.GetString(bytes);} 现在,您需要两种方法从其编码原始值的十六进制表示中获取字符串。 b $ b 祝你好运。希望这有帮助。You now have both methods you need to get a string from the hexadecimal representation of its encoded raw value.Good luck. Hope this helps.string hex = richTextBox1.Textint NumberChars = hex.Length;byte[] bytes = new byte[NumberChars / 2];for (int i = 0; i < NumberChars; i += 2)bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2).ToString(), 16);return bytes; 这篇关于如何在C#中读取SQL的varbinary作为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-05 09:04