Thursday, 20 March 2014

code to save image in database in c#

Mostly  we are not storing image into database server as it is very heavy and it takes lots of space. We are storing the image into server and storing the path into database.
But due to some reason we have to store the images into database, there is a simple code to store the image into database.

@Code Snippet for save image into database  
//Code to store image
        public void ImageStore(string fPath)
            // Read the file data into a byte array
            string filename = "";
            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
               byte[]   imageData = new Byte[fs.Length];
                fs.Read(imageData, 0, (int)fs.Length);
            //Sql connection
            string connectionString = @""; //defined connection string
            using (SqlConnection conn = new SqlConnection(connectionString))
                SqlCommand cmd = new SqlCommand("storeprocedure", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@filename", filename);
                cmd.Parameters["@filename"].Direction = ParameterDirection.Input;
                cmd.Parameters.Add("@blobdata", SqlDbType.Image);
                cmd.Parameters["@blobdata"].Direction = ParameterDirection.Input;
                // Store the byte array within the image field
                cmd.Parameters["@blobdata"].Value = imageData;

No comments:

Post a Comment