2

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

1
  • Please look at this question and its answers. Commented Jul 3, 2014 at 13:25

5 Answers 5

2

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Thats not really what I meant, but it will do :)
0

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; }
}

Comments

0

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, ... };

Comments

0

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();
 }
}

Comments

0

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#

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.