Article Menu
superdotnet originals
Intro Lessons
Tips and Tricks
Data Access
Quick Code
General ASP.NET
Windows Forms

All Articles
Most Viewed Articles
Search Articles

55,000+ developers and growing

Language Specs
Browse our HTML conversion of the C# Language Specification

Resource Options
Latest Web Additions

.NET Hosts

More Resources
Namespace List
More MSDN Links
QuickStart Lists

Add Resources
Add Listing
Add Host

Using Images and Files with SQL Server: Part 2

Article Categories: Data Access | Quick Code
Rated: | Number Of Ratings 15 | Add Rating/View Ratings
Page 1

The code for viewing the file (get_files.aspx) is just a few lines of code.

<% @Page Language="C#" %>
<% @Import Namespace="System.IO" %>
<% @ Import Namespace="System.Data" %>
<% @ Import Namespace="System.Data.SqlClient" %>
<script runat="server">

private void Page_Load(Object sender, EventArgs e) {

string sql="SELECT * FROM TestFiles WHERE ID = '" + Request.QueryString["ID"] + "'";
SqlConnection connection = new SqlConnection("server=localhost; uid=; pwd=; Database=myDB");

SqlCommand command = new SqlCommand(sql, connection);
SqlDataReader dr = command.ExecuteReader();

		Response.BinaryWrite( (byte[]) dr["MyFile"] );


Pretty easy. All we need to do is get the information from our table based on the ID, and then use the methods AddHeader to set the Content-Type of the page, and then use BinaryWrite to display the file. We're also using Clear() which clears any content output from the buffer stream (just to be on the safe side) before we write the file to the browser.

BinaryWrite just writes a string of binary character data to the HTTP output stream from a buffer. Our line (byte[]) dr["MyFile"] just converts our file data to a byte array which is then sent to the user.

The only thing to remember is that the user must have an application/viewer to view the file if it is a Word document, PDF file, etc. In Part 3 we'll look at file types, like .zip and exe files, and how to better make them available for download from SQL Server.

Page 1

Copyright 2002,2003 superdotnet.com, all rights reserved.
Original articles and site content may not be reproduced from our
site without consent from superdotnet.com.
      Privacy Policy and User Site Agreement