//This method is to browse the file object Private voidButton1_Click (Objectsender, EventArgs e) { //User Open File browse using(OpenFileDialog Dialog =NewOpenFileDialog ()) { //only one file can be selectedDialog. MultiSelect =false; //Select a file if(dialog. ShowDialog () = =DialogResult.OK) {Try { //give the selected file path to Txtpath This. TextBox1.Text =dialog. FileName; } Catch(Exception ex) {//Throw Exception Throw(ex); } } } } //Close Private voidButton3_Click (Objectsender, EventArgs e) { This. Close (); } //turn files into binary streams into the database Private voidButton2_Click (Objectsender, EventArgs e) {FileStream FS=NewFileStream (TextBox1.Text, FileMode.Open); BinaryReader BR=NewBinaryReader (FS); Byte[] Bydata= Br. Readbytes ((int) fs. Length); Fs. Close (); stringconn ="server=.; Database=testdb; Uid=sa; Pwd=sa"; SqlConnection myconn=NewSqlConnection (conn); MyConn. Open (); stringstr ="INSERT INTO pro_table (pro_name,pro_file) VALUES (' Test file ', @file)"; SqlCommand Mycomm=NewSqlCommand (str, myconn); Mycomm. Parameters.Add ("@file", Sqldbtype.binary, bydata.length); Mycomm. parameters["@file"]. Value =Bydata; Mycomm. ExecuteNonQuery (); MyConn. Close (); } //reads the binary stream read-write from the database and restores it to a file Private voidButton4_Click (Objectsender, EventArgs e) { stringconn ="server=.; Database=testdb; Uid=sa; Pwd=sa"; stringstr ="Select Pro_file from pro_table where pro_name= ' test file '"; SqlConnection myconn=NewSqlConnection (conn); SqlDataAdapter SDA=NewSqlDataAdapter (STR, conn); DataSet myds=NewDataSet (); MyConn. Open (); Sda. Fill (myds); MyConn. Close (); Byte[] Files= (byte[]) myds. tables[0]. rows[0]["Pro_file"]; BinaryWriter BW=NewBinaryWriter (File.Open ("D:\\2.RDLC", FileMode.OpenOrCreate)); Bw. Write (Files); Bw. Close (); }
C # file and binary mutual transfer database write read-out