[Go] C # implementation stores and reads Word files in SQL Server

Source: Internet
Author: User

SOURCE C # Implementation store and read Word files in SQL Server

To implement implementing a file to read and write to a Word file in SQL Server, you need to add the column of the image type to the table you want to access, and the sample table structure is:

    CREATE TABLE Contracts (          ID VARCHAR (),          contract_file IMAGE      );  

To store the word file in the Contract_file field of the database, you need to convert the file to a byte array with the following code:

/// Convert the file to a byte array/// <summary>              ///Convert a file to bytes/// </summary>              /// <param name= "FileName" ></param>              /// <returns></returns>               Public Static byte[] File2bytes (stringfileName) {FileStream FS=NewFileStream (FileName, FileMode.OpenOrCreate, FileAccess.Read); byte[] Filedatas =New byte[FS.                  Length]; Fs. Read (Filedatas,0, System.Convert.ToInt32 (fs.                  Length)); Fs.                  Close (); returnFiledatas; }  


The conversion completed byte[] is then stored to the corresponding field in the database:

     ///to store files in a database/// <summary>              ///Update Contract Documents/// </summary>              /// <param name= "id" ></param>              /// <param name= "filebytes" ></param>              /// <returns></returns>               Public BOOLUpdatecontractfile (stringIdbyte[] filebytes) {                  stringsql ="UPDATE Contracts SET [email protected]_file WHERE [email protected]"; using(SqlConnection conn =NewSqlConnection ( This. m_dataaccess.connectstring)) {Conn.                      Open (); using(SqlCommand cmd =NewSqlCommand ()) {cmd. Connection=Conn; Cmd.commandtext=SQL; Cmd.                                Parameters.clear (); Cmd. Parameters.Add (NewSqlParameter ("@CONTRACT_FILE", Sqldbtype.image)); Cmd. parameters["@CONTRACT_FILE"]. Value =filebytes; Cmd. Parameters.Add (NewSqlParameter ("@ID", SqlDbType.VarChar)); Cmd. parameters["@ID"]. Value =ID; returnCmd. ExecuteNonQuery () >0?true:false; }                  }              }  

To read a Word file stored in a database, you need to first convert the field of the image type to bytes[], as follows:

///get the file by ID byte array/// <summary>          ///Obtaining Contract Documents/// </summary>          /// <param name= "id" ></param>          /// <returns></returns>           Public byte[] Getcontractfile (stringID) {stringsql ="SELECT contract_file from contracts WHERE id= ' {0} '"; SQL=string.              Format (SQL, id); ObjectContractfile; Contractfile= This. m_dataaccess.executescalar (SQL); if(Contractfile = =NULL)              {                  return New byte[0]; }              Else              {                  return(byte[]) contractfile; }          } 


After obtaining the file's byte[], save the file through a file stream operation as a Word file, with the following code:

Store the byte[] array as a Word file

                       byte[] Filebytes = This. M_contractsbusiness.getcontractfile (ID); if(Filebytes.length = =0) {Xmessagebox.showerror ("No Contract Documents found! "); return; } SaveFileDialog SFD=NewSaveFileDialog (); SfD. Filter="Word file (*.doc) |*.doc"; if(SFD. ShowDialog () = =System.Windows.Forms.DialogResult.OK) {Try                              {                                  stringSavefilename =SFD.                                  FileName; intArraySize =New int();//watch this sentence .ArraySize = Filebytes.getupperbound (0); FileStream FS=NewFileStream (Savefilename, FileMode.OpenOrCreate, FileAccess.Write); Fs. Write (Filebytes,0, ArraySize); Fs.                                  Close (); if(Xmessagebox.showquestion ("file Download successful, do you want to open the file now? ") ==System.Windows.Forms.DialogResult.Yes) {                                  Process.Start (Savefilename); }                              }                              Catch(Exception ex) {Xmessagebox.showerror ("Download file failed! "); } 

[Go] C # implementation stores and reads Word files in SQL Server

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.