Getting bytes from a stream or file is quite a normal scenario & once you are able to retrieve the bytes, it can be saved in database as BLOB content as well. This is very handy way of storing any file type (text, audio, video, pdf, etc.) and then play around.
Below is C# implementation to do the same:
using System; using System.Collections.Generic; using System.IO; namespace Technical { public class StreamHandler { public static byte[] ReadBytes(Stream Input) { byte[] buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = Input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } public static byte[] ReadBytes(string FilePath) { byte[] buffer; FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read); try { int length = (int)fileStream.Length; buffer = new byte[length]; int count; int sum = 0; // read until Read method returns 0 (end of the stream has been reached) while ((count = fileStream.Read(buffer, sum, length - sum)) > 0) sum += count; // sum is a buffer offset for next reading } finally { fileStream.Close(); } return buffer; } } }
“ReadBytes” is an overloaded method that accepts either stream object or file name (with path) and returns the byte array.
Enjoy!!
(Visited 273 times, 1 visits today)