Monday 3 September 2012

Beginning .Net , C# Tips : Get or Retrieve stored file from SQL Server Database Table with C# Examples and VB.Net Examples

You can retrieve stored file from SQL Server Database Table and store as physical file in hard drive.
In earlier example we stored file into SQL Server Database table.

Here is example for this.
In this example we retrieved stored file from database record and store as physical file in hard drive.
We retrieved "product_document" column data and stored.

C# Examples :
        SqlCommand objCmd = new SqlCommand();
        SqlConnection objConn = new SqlConnection();
        SqlDataAdapter objAdapt = new SqlDataAdapter();
        DataSet Ods = new DataSet();
        objConn.ConnectionString = @"Data Source=.\SQLEXPRESS;" +
                                   "Initial Catalog=TempDatabase;" +
                                   "User ID=sa;Password=sa;";

        objConn.Open();
        objCmd.Connection = objConn;
        objCmd.CommandText = "select * from product_master where product_id=15";
        objAdapt.SelectCommand = objCmd;
        objAdapt.Fill(Ods);
        objConn.Close();
        string strFileName = Convert.ToString(Ods.Tables[0].Rows[0]["product_document_filename"]);
        Byte[] objByte = (Byte[])Ods.Tables[0].Rows[0]["product_document"];

        System.IO.File.WriteAllBytes(Server.MapPath("") + "/" + strFileName, objByte);

VB.net Examples :
        Dim objCmd As New SqlCommand()
        Dim objConn As New SqlConnection()
        Dim objAdapt As New SqlDataAdapter()
        Dim Ods As New DataSet()
        objConn.ConnectionString = "Data Source=.\SQLEXPRESS;" & _
                                    "Initial Catalog=TempDatabase;" & _
                                    "User ID=sa;Password=sa;"

        objConn.Open()
        objCmd.Connection = objConn
        objCmd.CommandText = "select * from product_master where product_id=15"
        objAdapt.SelectCommand = objCmd
        objAdapt.Fill(Ods)
        objConn.Close()
        Dim strFileName As String = Convert.ToString(Ods.Tables(0).Rows(0)("product_document_filename"))
        Dim objByte As [Byte]() = DirectCast(Ods.Tables(0).Rows(0)("product_document"), [Byte]())

        System.IO.File.WriteAllBytes(Server.MapPath("") & "/" & strFileName, objByte)

Click here to view "Insert or Save file into SQL Server Database Table with C# Examples and VB.Net Examples" article. Click Here...

This is very useful .Net Tips.

For Beginning .Net articles. Click Here...

Learn other ADO.Net Examples over here. Click Here...

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.



No comments:

Post a Comment