1. Write files to the database in binary stream format
Get the file path First, then save the file in binary readout in a binary array, connect to the database, assign the binary array to the corresponding parameter in the SQL statement, and finish writing the file to the database.
Copy Code code as follows:
Write a file stream to the database
</summary>
<param name= "FilePath" > The path to the database file </param>
<param name= The row designator of the insert file in the ID > Database id</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, from the database to read out the file and create the appropriate format of the file
To read a file from a database, simply create the appropriate file based on the path you want, and then write the binary stream stored in the database to the new file.
If the directory has a file with the same name, the original file will be overwritten
Copy Code code as follows:
Reading a file stream from the database
Shipmain. rows[0]["Zbdocument"], the full path to the file
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);//form files from data in the database
Fs. Write ((byte[]) Shipmain. rows[0]["Zbdocumentfile"], 0, arraysize);
Fs. Close ();
}