C # Save the file to the database or read the file from the database

Source: Internet
Author: User

In fact, the method is very simple, but it may be because these friends have not found a method at the moment since they just started programming.
The following describes how to use C # to complete this task.
First, we will introduce how to save files to the database.
Save the file to the database. In fact, after converting the file into a binary stream, save the binary stream to the corresponding fields of the database. In SQL Server, the Data Type of this field is Image, and in Access, the Data Type of this field is OLE object.
Copy codeThe Code is as follows:
// Save the file to the SQL Server database
FileInfo fi = new FileInfo (fileName );
FileStream fs = fi. OpenRead ();
Byte [] bytes = new byte [fs. Length];
Fs. Read (bytes, 0, Convert. ToInt32 (fs. Length ));
SqlCommand cm = new SqlCommand ();
Cm. Connection = cn;
Cm. CommandType = CommandType. Text;
If (cn. State = 0) cn. Open ();
Cm. CommandText = "insert into" + tableName + "(" + fieldName + ") values (@ file )";
SqlParameter spFile = new SqlParameter ("@ file", SqlDbType. Image );
SpFile. Value = bytes;
Cm. Parameters. Add (spFile );
Cm. ExecuteNonQuery ()
// Save the file to the Access Database
FileInfo fi = new FileInfo (fileName );
FileStream fs = fi. OpenRead ();
Byte [] bytes = new byte [fs. Length];
Fs. Read (bytes, 0, Convert. ToInt32 (fs. Length ));
OleDbCommand cm = new OleDbCommand ();
Cm. Connection = cn;
Cm. CommandType = CommandType. Text;
If (cn. State = 0) cn. Open ();
Cm. CommandText = "insert into" + tableName + "(" + fieldName + ") values (@ file )";
OleDbParameter spFile = new OleDbParameter ("@ file", OleDbType. Binary );
SpFile. Value = bytes;
Cm. Parameters. Add (spFile );
Cm. ExecuteNonQuery ()
// Save the client file to the database
SQL = "update t_mail set attachfilename = @ attachfilename, attachfile = @ attachfile where mailid =" + mailid;
MyCommand = new SqlCommand (SQL, new SqlConnection (ConnStr ));
String path = fl_name.PostedFile.FileName;
String filename = path. Substring (path. LastIndexOf ("\") + 1, path. Length-path.LastIndexOf ("\")-1 );
MyCommand. Parameters. Add ("@ attachfilename", SqlDbType. VarChar );
MyCommand. Parameters ["@ attachfilename"]. Value = filename;
MyCommand. Parameters. Add ("@ attachfile", SqlDbType. Image );
Stream fileStream = fl_name.PostedFile.InputStream;
Int intFileSize = fl_name.PostedFile.ContentLength;
Byte [] fileContent = new byte [intFileSize];
Int intStatus = fileStream. Read (fileContent, 0, intFileSize); // The file is Read to the fileContent array.
MyCommand. Parameters ["@ attachfile"]. Value = (byte []) fileContent );
FileStream. Close ();
MyCommand. Connection. Open ();
MyCommand. ExecuteNonQuery ();
MyCommand. Connection. Close ();

In the code, fileName is the complete name of the file, tableName is the name of the table to be operated, and fieldName is the field name of the file to be saved.
The two pieces of code are actually the same, but they are different in operating databases and using different objects.
Next, let's talk about reading files from the database and only reading from SQL Server.
Copy codeThe Code is as follows:
SqlDataReader dr = null;
SqlConnection objCn = new SqlConnection ();
ObjCn. ConnectionString = "Data Source = (local); User ID = sa; Password =; Initial Catalog = Test ";
SqlCommand cm = new SqlCommand ();
Cm. Connection = cn;
Cm. CommandType = CommandType. Text;
Cm. CommandText = "select" + fieldName + "from" + tableName + "where ID = 1 ";
Dr = cm. ExecuteReader ();
Byte [] File = null;
If (dr. Read ())
{
File = (byte []) dr [0];
}
FileStream fs;
FileInfo fi = new System. IO. FileInfo (fileName );
Fs = fi. OpenWrite ();
Fs. Write (File, 0, File. Length );
Fs. Close ();

The above Code reads the files stored in the database and saves the Files specified by fileName.
When using the above Code, do not forget to add System. Data. SqlClient and System. IO references.
Modify:
Read the following code of the file.
Copy codeThe Code is as follows:
FileStream fs;
FileInfo fi = new System. IO. FileInfo (fileName );
Fs = fi. OpenWrite ();
Fs. Write (File, 0, File. Length );
Fs. Close ();
Change
FileStream fs = new FileStream (fileName, FileMode. CreateNew );
BinaryWriter bw = new BinaryWriter (fs );
Bw. Write (File, 0, File. Length );
Bw. Close ();
Fs. Close ();

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.