1. Write files to the database in the format of binary streams
Obtain the file path, read the file in binary format, and store it in a binary array. Connect to the database and assign the binary array to the corresponding parameter in the SQL statement, write files to the database
Copy codeThe Code is as follows:
/// Write the file stream to the database
/// </Summary>
/// <Param name = "filePath"> path to the database file </param>
/// <Param name = "id"> row ID of the file inserted in the database </param>
/// <Returns> </returns>
Public int UploadFile (string filePath, string id)
{
Byte [] buffer = null;
Int result = 0;
If (! String. IsNullOrEmpty (filePath ))
{
String file = HttpContext. Current. Server. MapPath (filePath );
Buffer = File. ReadAllBytes (file );
Using (SqlConnection conn = new SqlConnection (DBOperator. ConnString ))
{
Using (SqlCommand cmd = conn. CreateCommand ())
{
Cmd. CommandText = "update DomesticCompanyManage_Main_T set ZBDocumentFile = @ fileContents where MainID = '" + id + "'";;
Cmd. Parameters. AddRange (new [] {
New SqlParameter ("@ fileContents", buffer)
});
Conn. Open ();
Result = cmd. ExecuteNonQuery ();
Conn. Close ();
}
}
Return result;
}
Else
Return 0;
}
2. Read files from the database and create files in the corresponding format
To read files from the database, you only need to create the corresponding files according to the required path, and then write the binary stream stored in the database to the new file.
If a file with the same name exists in the directory, the original file will be overwritten.
Copy codeThe Code is as follows:
// Read the file stream from the database
// Shipmain. Rows [0] ["ZBDocument"], full file path
// Shipmain. Rows [0] ["ZBDocumentFile"], the file stream stored in the database
If (shipmain. Rows [0] ["ZBDocumentFile"]! = DBNull. Value)
{
Int arraySize = (byte []) shipmain. Rows [0] ["ZBDocumentFile"]). GetUpperBound (0 );
FileStream fs = new FileStream (HttpContext. current. server. mapPath (shipmain. rows [0] ["ZBDocument"]. toString (), FileMode. openOrCreate, FileAccess. write); // a file is formed by data in the database.
Fs. Write (byte []) shipmain. Rows [0] ["ZBDocumentFile"], 0, arraySize );
Fs. Close ();
}