Blog
    C#
    ADO.Net
    .NET
    ASP.Net & Web Forms
    Custom Controls
    Web Development
    Exception Handling
    XML
    Database
    Security in .Net
    Testing
    Web Services
    Windows Services
    Windows Controls
    WCF
    AJAX
    WPF
    XAML
    Reporting
    Setup
    VB.Net
    LINQ
    JQuery
    SilverLight
    JavaScript
    HTML5
    Crystal Report
    Cloud Computing
    Share Point
    Visual C++
    MVC
    Android
    PHP
    Java
    HTML
    WordPress
    Joomla
    Products
    Drupal
    Windows Phone
    JSON
Follow Us
Follow _MindStick_ on Twitter View MindStick Software's LinkedIn profile View MindStick Software's Facebook profile
Top Contributor
Advertisement
Advertise with Us
Mindstick
Article Article  Forum Forum  Blog Blog  Quiz Quiz  Beginner Beginner  Careers Careers  Contact Contact  Login Login  
Home | Product | Services | About Us | Interview | DeveloperSection | Submit an Article | Submit Blog
Report Abuse Form
Reason:    
 

Home >> C# >> Save image in SqlServer using C#.
Save image in SqlServer using C#.

Hi... In this blog I will tell you that how to save images in sqlserver by using c#. We will use System.Data.SqlClient namespace to work with sqlserver and we will use System.IO namespace to work with file streams.
Views: 5890     Comments: 3
by Awadhendra Tiwari on 5/21/2011

Save image in Sql Server using C#

In this blog I will tell you that how to save image in Sql Server using c#. Here I will give you necessary steps to store image in sql server.

1)      Before we are starting to make application in C# firstly we need to create a table in sql server where we store out image. Here I will create a table named ImageTable in which I will store image. ImageTable contains two column one is imageID which will store id of image in image table. And other column which have name imageData is stored image in format of binary.

Here I will provide a sample sql code snippet to create ImageTable

create table ImageTable

(

     imageID int,

     imageData image

)

2)      Now import System.Data.SqlClient namespace in your project. This namespace provide you all necessary classes and interfaces which is necessary to establish connection to SqlServer.

3)      Create following methods and call it according to your requiremnt.

/// <summary>

        /// On click event of browse button write down following code. This

        /// Will display a open file dialog box which will ask to choose you

        /// image and will store path of image in textbox.

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void button1_Click(object sender, EventArgs e)

        {

            OpenFileDialog ofd = new OpenFileDialog();

            if (DialogResult.OK == ofd.ShowDialog())

            {

                textBox1.Text = ofd.FileName;   //storing path of image in textbox.

            }

        }

        /// <summary>

        /// On the click of SaveButton call saveImageInDataBase(int imgId) method

        /// which will save image in database.

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void button2_Click(object sender, EventArgs e)

        {

            saveImageInDataBase(1);

        }

        /// <summary>

        /// This is a required method which will save image in database.

        /// </summary>

        /// <param name="imageID"></param>

        public void saveImageInDataBase(int imageID)

        {

            byte[] imageData = ReadImageFile(textBox1.Text);    //This nethod returns image in byte array format.

            SqlConnection con = new SqlConnection();

            con.ConnectionString = "Data Source=aaaa;User ID=sa;Password=abcd;Initial Catalog=Workbook";  //provide connection string of your server.

            con.Open();   //open connection to server.

            string query = "insert into ImageTable values(@imageId,@imageData)";     //create a query variable.

            SqlCommand cmd = new SqlCommand(query, con);          //create a sqlcommand object.

            cmd.Parameters.Add(new SqlParameter("@imageId", imageID));    //add first parameters.

            cmd.Parameters.Add(new SqlParameter("@imageData", imageData));    //add second parameters.

            int rows = cmd.ExecuteNonQuery();         //execute query.

            if (rows > 0)

                MessageBox.Show("Image saved.");

            else

                MessageBox.Show("Unable to save image.");

            con.Close();

        }

        /// <summary>

        /// This method will converts image in byte array format and returns to its caller.

        /// use System.IO namespace regarding streaming concept.

        /// </summary>

        /// <param name="imageLocation"></param>

        /// <returns></returns>

        public byte[] ReadImageFile(string imageLocation)

        {

            byte[] imageData = null;

            FileInfo fileInfo = new FileInfo(imageLocation);

            long imageFileLength = fileInfo.Length;

            FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);

            BinaryReader br = new BinaryReader(fs);

            imageData = br.ReadBytes((int)imageFileLength);

            return imageData;

        }

    }


very good
by aken H on 9/9/2011

hi  Awadhendra Tiwari

    i appreciation you write technical article.

thanks for your article.

Report Abuse

Save image in Sql Server using C#
by John Smith on 9/14/2011
nice blog...
Report Abuse

Save image in Sql Server.
by James Smith on 10/1/2011
Hey Awadhendra,
Good one..

Thanks for sharing it with us.
Report Abuse
Title :  
Comment :
Text ColorBackground Color
BoldItalicUnderline
LeftCenterRightJustify
Ordered ListBulleted List
IndentOutdent
Horizontal Rule
SubscriptSuperscript
HyperlinkImage
Design ModeDesign
View HtmlHtml
      
 
Report Abuse Form
Reason:    
 
Latest Article
    
    
    
    
    
    
    
    
    
    
More...
Latest Blogs by Awadhendra Tiwari
    
    
    
    
    
    
    
    
    
    
More...
Top Viewed Articles
    
    
    
    
    
    
    
    
    
    
Top Viewed Blogs
    
    
    
    
    
    
    
    
    
    
Latest Interview Questions
    
    
    
    
    
    
    
    
    
    
More...
Total Online Users: 3058
Dudelabs
Copyright © 2009 - 2012 MindStick. All Rights Reserved.