<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>dotnet thoughts &#187; File to Database</title>
	<atom:link href="http://www.dotnetthoughts.net/tag/file-to-database/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dotnetthoughts.net</link>
	<description>a dotnet developer&#039;s technical blog</description>
	<lastBuildDate>Wed, 08 Feb 2012 03:18:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>How to Store and Retrieve files from SQL Server Database</title>
		<link>http://www.dotnetthoughts.net/2009/10/07/how-to-store-and-retrieve-files-from-sql-server-database/</link>
		<comments>http://www.dotnetthoughts.net/2009/10/07/how-to-store-and-retrieve-files-from-sql-server-database/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 07:41:48 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[File to Database]]></category>
		<category><![CDATA[IIS 7]]></category>

		<guid isPermaLink="false">http://anuraj.wordpress.com/?p=417</guid>
		<description><![CDATA[The forum I joined recently got lot of queries like How to Save Images in the Database, How to save files in SQL Server, How read files from Database etc. So I thought of writing a post regarding this. Even &#8230; <a href="http://www.dotnetthoughts.net/2009/10/07/how-to-store-and-retrieve-files-from-sql-server-database/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The forum I joined recently got lot of queries like How to Save Images in the Database, How to save files in SQL Server, How read files from Database etc. So I thought of writing a post regarding this. Even though I am part of a Web project, I am doing some Windows applications for the client. So I thought it will nice to brush-up the ASP.Net skills.</p>
<p>Here is the code. I am using SQL Server 2008, but I am not using FileStream for the current project, I already wrote a <a href="http://www.dotnetthoughts.net/2009/09/22/adding-and-reading-files-from-sql-server-2008-filestream/">post</a> to how to<br />
manage files with FileStream feature. In this post I am using nvarchar(MAX) datatype for storing the file content.</p>
<p><strong>Table Design</strong></p>
<pre class="brush: sql; title: ; notranslate">
CREATE TABLE [dbo].[tblFiles](
	[FileId] [uniqueidentifier] NOT NULL,
	[Filename] [nvarchar](255) NOT NULL,
	[FileContent] [varbinary](max) NULL
)
</pre>
<p>And the I set FileId default to newId() and FileContent default to NULL</p>
<pre class="brush: sql; title: ; notranslate">
ALTER TABLE [dbo].[tblFiles] ADD  CONSTRAINT [DF_tblFiles_FileId]  DEFAULT (newid()) FOR [FileId]
GO
ALTER TABLE [dbo].[tblFiles] ADD  CONSTRAINT [DF_tblFiles_FileContent]  DEFAULT (NULL) FOR [FileContent]
GO
</pre>
<p>I wrote the code in C#. I am having a Asp FileUpload control and a button to upload the file, and a Repeater control with two controls, a label for displaying the filename and hyper link control for downloading the file.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;body&gt;
&lt;form runat=&quot;server&quot;&gt;
&lt;asp:FileUpload runat=&quot;server&quot; ID=&quot;fileUploadImage&quot; /&gt;
&lt;asp:Button runat=&quot;server&quot; ID=&quot;cmdUpload&quot; Text=&quot;Upload File&quot; OnClick=&quot;cmdUpload_Click&quot; /&gt;
&lt;asp:Repeater runat=&quot;server&quot; ID=&quot;rptrFiles&quot;&gt;
    &lt;HeaderTemplate&gt;
        &lt;table&gt;
    &lt;/HeaderTemplate&gt;
    &lt;ItemTemplate&gt;
        &lt;tr&gt;
            &lt;td&gt;
                &lt;asp:Label runat=&quot;server&quot; ID=&quot;lblFilename&quot; Text='&lt;%# Eval(&quot;FileName&quot;)%&gt;' /&gt;
            &lt;/td&gt;
            &lt;td&gt;
              &lt;asp:HyperLink runat=&quot;server&quot; Target=&quot;_blank&quot; ID=&quot;lbtDownload&quot; Text=&quot;Download&quot; NavigateUrl='&lt;%# &quot;Download.aspx?File=&quot;  + Eval(&quot;FileId&quot;).ToString() %&gt;' /&gt;
            &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/ItemTemplate&gt;
    &lt;FooterTemplate&gt;
        &lt;/table&gt;
    &lt;/FooterTemplate&gt;
&lt;/asp:Repeater&gt;
&lt;/form&gt;
&lt;/body&gt;
</pre>
<p><strong>Uploading the File to the Database</strong><br />
Code behind</p>
<pre class="brush: csharp; title: ; notranslate">
protected void cmdUpload_Click(object sender, EventArgs e)
{
    string fileName = Path.GetFileName(this.fileUploadImage.FileName);
    byte[] fileContent = this.fileUploadImage.FileBytes;
    using (SqlConnection connection = new SqlConnection(&quot;Server=.\\SQLEXPRESS;User Id=sa;Password=sapassword;Database=sampledb&quot;))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand(&quot;INSERT INTO tblFiles(Filename, FileContent) VALUES(@Filename, @FileContent)&quot;, connection))
        {
            SqlParameter fileNameParameter = new SqlParameter(&quot;@Filename&quot;, System.Data.SqlDbType.NVarChar, 255);
            fileNameParameter.Value = fileName;
            SqlParameter fileContentParameter = new SqlParameter(&quot;@FileContent&quot;, System.Data.SqlDbType.VarBinary);
            fileContentParameter.Value = fileContent;
            command.Parameters.AddRange(new SqlParameter[] { fileNameParameter, fileContentParameter });
            command.ExecuteNonQuery();
        }
    }
}
</pre>
<p>And here is code to bind the repeater from the Database</p>
<pre class="brush: csharp; title: ; notranslate">
DataTable dtFiles = new DataTable(&quot;Files&quot;);
using (SqlDataAdapter adapter = new SqlDataAdapter(&quot;SELECT FileId, FileName FROM tblFiles&quot;, &quot;Server=.\\SQLEXPRESS;User Id=sa;Password=sapassword;Database=sampledb&quot;))
{
    adapter.Fill(dtFiles);
}
this.rptrFiles.DataSource = dtFiles;
this.rptrFiles.DataBind();
</pre>
<p><strong>Download / Read the file from Database</strong><br />
And to download / read the file from Database, I am passing the File unique id to another page(download.aspx).I this page I am checking for the File querysting and based on that reading filecontent from Sql and writing it to Asp.net output stream. You can get more information about how to download files from IIS in this <a href="http://www.dotnetthoughts.net/2007/05/06/download-files-from-iis-server-using-aspnet/">post</a>.</p>
<pre class="brush: csharp; title: ; notranslate">
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString[&quot;File&quot;] != null)
    {
        string fileId = Request.QueryString[&quot;File&quot;];
        using (SqlConnection connection = new SqlConnection(&quot;Server=.\\SQLEXPRESS;User Id=sa;Password=sapassword;Database=Sample&quot;))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand(&quot;SELECT Filename, FileContent FROM tblFiles WHERE FileId = @FileId&quot;, connection))
            {
                command.Parameters.AddWithValue(&quot;@FileId&quot;, fileId);
                SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
                if (reader.HasRows)
                {
                    reader.Read();
                    byte[] content = reader[&quot;FileContent&quot;] as byte[];
                    string filename = reader[&quot;FileName&quot;].ToString();
                    Response.Clear();
                    Response.ClearContent();
                    Response.AddHeader(&quot;Content-Disposition&quot;, &quot;attachment; filename=&quot; + filename);
                    Response.AddHeader(&quot;Content-Length&quot;, content.Length.ToString());
                    Response.OutputStream.Write(content, 0, content.Length);
                    Response.End();
                }
            }
        }
    }
}
</pre>
<p>Please write to me if I missed something. Happy Programming .</p>
<div class="betterrelated"><p><strong>Related content:</strong></p>
<ol><li> <a href="http://www.dotnetthoughts.net/2009/09/22/adding-and-reading-files-from-sql-server-2008-filestream/" title="Permanent link to Adding and Reading files from SQL Server 2008 Filestream">Adding and Reading files from SQL Server 2008 Filestream</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2009/07/06/filestream-in-sql-server-2008/" title="Permanent link to FILESTREAM in SQL Server 2008">FILESTREAM in SQL Server 2008</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2009/10/22/implementing-custom-paging-in-datarepeater-using-c-and-sql-server/" title="Permanent link to Implementing Custom Paging in DataRepeater using C# and SQL Server">Implementing Custom Paging in DataRepeater using C# and SQL Server</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2008/05/08/using-iocompression-namespace/" title="Permanent link to Using IO.Compression namespace">Using IO.Compression namespace</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2009/09/30/convert-image-to-icon-using-c/" title="Permanent link to Convert Image to Icon using C#">Convert Image to Icon using C#</a>  </li>
</ol></div>]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/10/07/how-to-store-and-retrieve-files-from-sql-server-database/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

