|
|
GetBytes() issue - attemting to load into a MemoryStream object |
|
Author |
Message |
Tryst

|
Posted: .NET Framework Data Access and Storage, GetBytes() issue - attemting to load into a MemoryStream object |
Top |
Hi all,
I have a column in my database that is of type image (bytes) and what to load this data into a System.IO.MemoryStream object but can't seem to find out how to do it. Hopefully, someone out there would have had experience of doing this and can show me the way. I have the following code...
System.IO.MemoryStream stream = new System.IO.MemoryStream(objSqlCeDataReader.GetBytes(0, 0, null, 0, int.MaxValue));
...which I know is wrong as I think this call to GetBytes() only returns the size/length of the total bytes as I am passing in a null buffer (3rd param). How can I do the database call and pass it into the MemoryStream object in one scoop
Thanks
.NET Development1
|
|
|
|
 |
cverdon

|
Posted: .NET Framework Data Access and Storage, GetBytes() issue - attemting to load into a MemoryStream object |
Top |
Hi,
Take a look at this article for sample code: http://www.codeproject.com/cs/database/images2db.asp
Charles
|
|
|
|
 |
David Hayden

|
Posted: .NET Framework Data Access and Storage, GetBytes() issue - attemting to load into a MemoryStream object |
Top |
I have written a couple of tutorials on the subject:
Saving and Retrieving Images From SQL Server Using DAAB
Saving and Displaying Photos in SQL Server using ASP.NET and FileUpload Control
Here is a snippet of code:
private Image RetrieveImage(int photoId) { Image image = null;
using (SqlConnection connection = new SqlConnection("...")) { using (SqlCommand command = connection.CreateCommand()) { command.CommandText = "SELECT Photo FROM Photos
"; command.Parameters.AddWithValue("
", photoId);
connection.Open(); byte[] imageData = (byte[])command.ExecuteScalar();
MemoryStream memStream = new MemoryStream(imageData); image = Image.FromStream(memStream); } }
return image; }
Regards,
Dave
|
|
|
|
 |
alazela

|
Posted: .NET Framework Data Access and Storage, GetBytes() issue - attemting to load into a MemoryStream object |
Top |
And to include the minimal change from the original, non-working snippet (this assumes the type is Binary, VarBinary, Image or Timestamp in order to return a byte array from GetValue):
System.IO.MemoryStream stream = newSystem.IO.MemoryStream((byte[])objSqlCeDataReader.GetValue(0));
Alternatively, if you want this to work with other types that don't return byte arrays by default, but that work with GetBytes():
byte[] buffer = new byte[objSqlCeDataReader.GetBytes(0, 0, null, 0, int.MaxValue)]; long length = objSqlCeDataReader.GetBytes(0, 0, buffer, 0, buffer.Length); System.IO.MemoryStream stream = newSystem.IO.MemoryStream(buffer, 0, length);
|
|
|
|
 |
Tryst

|
Posted: .NET Framework Data Access and Storage, GetBytes() issue - attemting to load into a MemoryStream object |
Top |
ok - thanks for the feedback, guys!
|
|
|
|
 |
|
|