How to store image file in Sql server database?

Answer Posted / amit kumar sharma

//use this code to store image file in sql server database

//get directory Path(C:\\Temp) where image has stored and
use these two method in ur program

private void GetImagePath(string strDirectoryPath)
{
DirectoryInfo mobjDirInfo = new DirectoryInfo
(strDirectoryPath);
//object[] mobjStore = new object
[Directory.GetFiles(strDirectoryPath, "*.JPG").Length];
int counter =1;
foreach (FileInfo fl in mobjDirInfo.GetFiles
("*.JPG"))
{
// Create a new stream to load this photo
into
FileStream stream = new FileStream
(fl.FullName.ToString(), FileMode.Open, FileAccess.Read);

// Create a buffer to hold the stream bytes
byte[] buffer = new byte[stream.Length];

// Read the bytes from this stream
stream.Read(buffer, 0, (int)stream.Length);

// Now we can close the stream
stream.Close();

// Extract out the name of the file an use
it for the name of the photo
string strName =
Path.GetFileNameWithoutExtension(fl.Name.ToString());

// Insert the image into the database and
add it to the tree
InsertImageIntoDatabase(ref buffer,
strName, counter);
buffer = null;
counter = counter+1;
}
}


//Insert Images into sql server (create table TBLIMAGE
(PHOTOID int,PHOTONAME varchar(20),PHOTO IMAGE))
private void InsertImageIntoDatabase(ref byte[]
buffer, string strPhotoName, int intPhotoid)
{
if (mobjConn.State == ConnectionState.Closed)
{
mobjConn.Open();
}

mobjCmd = new SqlCommand("Insert Into TBLIMAGE
values(@PHOTOID,@PHOTONAME,@PHOTO)", mobjConn);
mobjCmd.Parameters.Add("@PHOTOID", intPhotoid);
mobjCmd.Parameters.Add
("@PHOTONAME",strPhotoName);
mobjCmd.Parameters.Add("@PHOTO", buffer);
mobjCmd.ExecuteNonQuery();

}

//if u have any query please revert back

Is This Answer Correct ?    9 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are Namespaces?

992


What to implement on my class Finalize or IDisposable

749


Is list ienumerable c#?

811


What are the classes contained in a single .NET DLL ?

707


Distinguish between system.string and system.text.stringbuilder classes?

705


Explain attributes in c#?

648


What is the difference between const and readonly in c#.net?

718


What is Private Constructor? and it’s use? Can you create instance of a class which has Private Constructor?

773


How to generate strong name key file or which command is used to generated strong name key file?

739


Can you have parameters for static constructors?

728


Explain About DTS package

762


You are designing a user control. You created new property called backgroundimage which is of type image. You wanted to disable storing this property in the user’s form. How to achieve this?

740


Is datetime a value type in c#?

673


What is the diff between the System.Array.CopyTo() and System.Array.Clone()?

789


Explain get and set accessor properties?

681