简体   繁体   中英

C# Create byte array in code from copied SQL value?

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

您可以将默认文件包含在项目中,然后使用其内容设置对象的值,例如

MyObject.filebytes = File.ReadAllBytes("default.bin");

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM