Store or save files/documents in SQL Server database using C#
Introduction
This sample will explain you how you can store files or documents in SQL Server database. In general, it's not a good idea to store files in databases because it can grow database rapidly and can cause slower performance of database and server. Ideally you should use file system to store files. But there may be scenarios where you may want to store files in database.Download Sample
How to store files in SQL Server database
To store a file in sql server, you need to read file data into a byte array. Once you have file data in byte array, you can easily store this file data in sql server using sql parameters. Following code explains you how to do this.Following code explains how to read file data in a byte array.
How to read file data bytes from SQL Server table
To read files from SQL Server, prepare a dataset first which will hold data from SQL Server table. Bind this dataset with a gridview control on form.Once you have image data in dataset DS, get file data from in a byte array.
Finally save byte array data to a file
How to download and run program
- Download sample from link on top. Extract in a folder.
- Restore SQL Server database from SQL Database sub folder.
- If somehow you can not restore provided database, you can generate necessary table using script(SQLScript.txt) provided in SQL Database directory.
- Open solution and Run it. Change connection string for your database.
- Click on Connect button. To add new file to database, click on New File button. Click Browse button in New File window to select a file. Then click on Save to save it.
Requirements
- Visual Studio.Net 2008
- .Net Framework 2.0
- MS SQL Server database (any version)
No comments:
Post a Comment