If (UpFile。 HasFile){// Judge whether there is a file.
If (checkfiletype (upfile.filename)) {//Determines the file type.
AddFile(UpFile。 File name, upload file. file content); //Call the AddFile method
rptFiles。 DataBind(); }//Data binding
}
}
///method to add files
///Input parameters: file name and file stream upload.
///Output Parameter: None
Private void AddFile (string file name, system. IO. streaming)
{
Sqlconnectioncon = new sqlconnection(...)// Create a new database connection.
SqlCommand cmd = new SqlCommand ("Insert file (file name) value (@ file name;" +" SELECT @ Identity = SCOPE _ Identity()",con); //
cmd。 Parameters.addwithvalue ("@ filename", file name); //Parameter assignment
SqlParameter idParm = cmd。 Parameter. Add("Identity ",SqlDbType. int);
idParm。 Direction = parameter direction. Output;
Using (con){// Use using for garbage collection.
con . Open(); //Open the database connection
cmd。 ExecuteNonQuery(); //execute the insert statement
int newFileId = (int)idParm。 Value; //Convert the value of idParm into an integer and assign it to newFileID.
StoreFile(newFileId,upload,con); //Call the file saving method.
}
}
///Save file method StoreFile
///Input parameters: file number fileID, file stream upload and connection command connection.
///Input parameter: None
Private void StoreFile(int fileId, stream upload, SqlCommand connection) {
Int bufferLen = 8040// Declare the variable bufferLen and assign 8040.
BinaryReader br = new binary reader (upload); //Instantiate the binary reader and read the upload stream.
byte[] chunk = br。 read bytes(buffer len); //Reads a bufferLen byte array from the stream, promotes the current position to bufferLen and stores it in the chunk array.
SqlCommand cmd = new SqlCommand ("update fileset filebytes = @ buffer where fileid = @ fileid", connection);
cmd。 parameters . AddWithValue(@ FileId,FileId); //Parameter assignment
cmd。 Parameter. Add("@Buffer ",SqlDbType. VarBinary、bufferLen)。 Value = chunk; //Parameter assignment
cmd。 ExecuteNonQuery(); //Execute the update statement
Sqlcommand cmdapend = new sqlcommand ("update file set FileBytes. WRITE(Buffer, Null, 0) where FileId=@FileId ",connection);
cmdAppend。 parameters . AddWithValue(" @ FileID ",FileID);
cmdAppend。 Parameter. Add("Buffer ",SqlDbType. VarBinary,buffer len);
chunk = br。 read bytes(buffer len);
And (chunk. Length & gt0){// Read the data stream circularly.
cmdAppend。 Parameter ["@Buffer"]. Value = chunk;
cmdAppend。 ExecuteNonQuery();
chunk = br。 read bytes(buffer len);
}
br。 close(); //close BinaryReader
}