C # Save the image file to the SQL Server database, then read the file and display it

Source: Internet
Author: User

Create a database test in SQL Server, and then create a data table imagetable in test,
The field ID int is automatically increased.
ImagePath nchar (50)
Image image type

CodeAs follows:

Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. text;
Using system. Windows. forms;
Using system. Data. sqlclient;
Using system. IO;

Namespace saveimagetosqlserver
{
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}

Private void buttonsaveimagetodataserver_click (Object sender, eventargs E)
{
This. folderbrowserdialog1.showdialog ();

String dirname = This. folderbrowserdialog1.selectedpath;
Directoryinfo dir = new directoryinfo (dirname );
Fileinfo [] fileinfos = dir. getfiles ("*. jpg "); // obtain all JPG files in the folder. Because the image files are large, do not select too many images in the folder. Otherwise, the primary area will be full, the system will prompt that no data can be inserted.
List <string> filelist = new list <string> (100 );
Foreach (fileinfo in fileinfos)
{
Filelist. Add (fileinfo. fullname );
System. Windows. Forms. application. doevents ();
}

# Region save data to data server
String strconn = // set the connection string. I am connected on the local machine. If it is remote, You need to modify the connection string.
@ "Server = (local );"
+ @ "Initial catalog = test ;"
+ @ "User ID = fisherman ;"
+ @ "Password = ;"
+ @ "Integrated Security = true ";

Try
{
Using (sqlconnection = new sqlconnection (strconn) // use using to release resources in time
{
Sqlconnection. open ();
Foreach (string file in filelist)
{
// The image file is stored in the database and needs to be converted to a binary stream first. Use byte [] to save.
Filestream = new filestream (file, filemode. Open, fileaccess. Read );
Byte [] byteimage = new byte [filestream. Length];
Filestream. Read (byteimage, 0, (INT) filestream. Length );

// Write code at ordinary times. For insert statements, you prefer to directly use "insert into tablename (a, B) values (A1, B1)", but for binary streams, write it like this
// An error is reported. The parameter name type must be set as follows.
String commandtext = "insert into imagetable (ImagePath, image) values (@ ImagePath, @ image )";
Sqlcommand = new sqlcommand (commandtext, sqlconnection );
Sqlcommand. Parameters. Add ("@ ImagePath", sqldbtype. Text); // image file path
Sqlcommand. Parameters. Add ("@ image", sqldbtype. Binary); // image file data in binary format.
Sqlcommand. Parameters ["@ ImagePath"]. value = file;
Sqlcommand. Parameters ["@ image"]. value = byteimage; // assign an image to command

Sqlcommand. executenonquery ();

System. Windows. Forms. application. doevents ();
}
Sqlconnection. Close (); // close must be displayed after use
}
}
Catch (sqlexception ex)
{
MessageBox. Show (ex. tostring ());
}
# Endregion
MessageBox. Show ("save data OK .");
}

Private void buttonshowimage_click (Object sender, eventargs E)
{
// Connection string, same as above
String strconn =
@ "Server = (local );"
+ @ "Initial catalog = test ;"
+ @ "User ID = fisherman ;"
+ @ "Password = ;"
+ @ "Integrated Security = true ;";

Try
{
Using (sqlconnection = new sqlconnection (strconn ))
{
Sqlconnection. open ();
String commandtext = "select ImagePath, image from imagetable"; // query data in imagetable
Sqldataadapter adapter = new sqldataadapter (commandtext, sqlconnection); // use a datatable to save data so that the value is assigned to the datagridview. After the function is completed, the datagridview on the form is displayed, with two columns, one column is image.
// The spacing between row and column is too small to be nice, but at least the image can be displayed.
Datatable dt = new datatable ();
Adapter. Fill (DT );
This. Maid = DT;
Sqlconnection. Close ();
}
}
Catch (sqlexception ex)
{
MessageBox. Show (ex. tostring ());
}
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.