Reputation: 951
I stored a file in SQL server as a byte array. However, I want that file to be a default value when I initialize the database. The initialization is done in code (inserting some fixed values etc). If I look into SQL server I see the file's value, something like 0x89504E4...... How can I set a C# property (byte[]) to this value? MyObject.filebytes = 0x89504E4...... obviously won't work.
Thanks
Upvotes: 2
Views: 960
Reputation: 106
Pass copied value from database to GetBinaryFromHexaString function and it will return the string data.
public static string GetBinaryFromHexaString (string hexa)
{
byte[] data = null;
string retData = string.Empty;
List<byte> bList = new List<byte>();
try {
for (int i = 2; i < hexa.Length - 1; i+=2) {
string hStr = hexa.Substring(i, 2);
byte b = byte.Parse(hStr, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
bList.Add (b);
}
data = bList.ToArray();
retData = System.Text.Encoding.UTF8.GetString(data);
}
catch {}
return retData;
}
Reference: Convert string to System.Data.SqlTypes.SqlBytes C#
Upvotes: 0
Reputation: 4893
Assuming you are attempting to load byte array off sql server returned result set you can do the following. For example, if you get a SqlDataReader back from ExecuteReader call on sql command "SELECT mybytecolumn from mytable":
public byte[] GetBytes(SqlDataReader reader)
{
const int MAXBUFFER = 4096;
byte[] buffer = new byte[MAXBUFFER]
using(MemoryStream ms = new MemoryStream())
{
int start = 0;
long length;
do
{
// Following is assuming column 0 has the byte data on the returned result set
length = reader.GetBytes(0, start, buffer, 0, MAXBUFFER);
ms.Write(buffer, 0, (int)length);
}
while(length == MAXBUFFER);
return ms.ToArray();
}
}
Upvotes: 0
Reputation: 63732
Close enough. You can either load it from an embedded resource or a file, or if it's just a short string, you could use the array initializer syntax:
MyObject.FileBytes = new byte[] { 0x89, 0x50, 0x4E, ... };
Upvotes: 0
Reputation: 453
You can include your default file in project and then set value of your object with it's contents, like
MyObject.filebytes = File.ReadAllBytes("default.bin");
Upvotes: 2
Reputation: 61401
If I understand your question correctly, you could create property inside that class that is array of bytes, then you could read the file from wherever you please be it file or database.
public class MyObject
{
public byte[] File { get; set; }
}
Upvotes: 0