| static byte[] RetrieveFile(string filename) { SqlConnection connection = new SqlConnection("Server=(local) ; Initial Catalog = FileStore ; Integrated Security = SSPI"); SqlCommand command = new SqlCommand("SELECT * FROM MyFiles WHERE Filename=@Filename", connection); command.Parameters.AddWithValue("@Filename", filename); connection.Open(); SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.SequentialAccess); reader.Read(); MemoryStream memory = new MemoryStream(); long startIndex = 0; const int ChunkSize = 256; while (true) { byte[] buffer = new byte[ChunkSize]; long retrievedBytes = reader.GetBytes(1, startIndex, buffer, 0, ChunkSize); memory.Write(buffer, 0, (int)retrievedBytes); startIndex += retrievedBytes; if (retrievedBytes != ChunkSize) break; } connection.Close(); byte[] data = memory.ToArray(); memory.Dispose(); return data; } |