C# 将RTF文档保存到SQLITE当中




表的结构


CREATE TABLE [DATA_TBL](
 [ID] VARCHAR PRIMARY KEY,
 [TITLE] TEXT,
 [RTF] BINARY,
 [TAG] TEXT);


using System.Data.SQLite;

string ConnectionString = "Data Source = test.db; Version=3";



保存 

//根据ID 将RTF文档保存到对应的记录的里面
public bool UpdateFile(string id,byte[] byteFile) {
    int result = -1;
    using (SQLiteConnection conn = new SQLiteConnection(ConnectionString)) {
        conn.Open();
        using (SQLiteCommand cmd = new SQLiteCommand(conn)) {
            string sql = $"UPDATE DATA_TBL SET RTF=@RTF WHERE ID=@ID";
            cmd.CommandText = sql;
            cmd.Parameters.Add("@ID",DbType.String).Value = id;
            cmd.Parameters.Add("@RTF",DbType.Binary).Value = byteFile; // 这个字段要 设置成 BINARY
            result = cmd.ExecuteNonQuery();
         }
     }
     return result != -1 ? true : false;
 }

      //直接保存
       public bool UpdateFile(string id,string Rtf) {
            byte[] byteArray = System.Text.Encoding.Default.GetBytes(Rtf);
            return UpdateFile(id,byteArray);
        }

调用

根据一个存在的RTF文件读取然后保存到数据库中

string id = "292450";//abaya
string path = @"C:\1.rtf";
byte[] b = File.ReadAllBytes(path);
UpdateFile(id,b);


直接将RichTextBox中的内容保存到数据库中

string id = "292440";//abashment
string rtf = richTextBox1.Rtf;
UpdateFile(id,rtf);


image


读取


        //根据ID 从数据库中得到文件的二进制内容
        public byte[] GetBytes(string id) {
            string sql = $"SELECT * FROM DATA_TBL WHERE id='{id}';";
            byte[] bt = null;
            DataTable dt = new DataTable();
            using (SQLiteConnection conn = new SQLiteConnection(ConnectionString)) {
                using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(sql,conn)) {
                    adapter.Fill(dt);
                    object obj = dt.Rows[0]["RTF"];
                    if (obj != null && obj != DBNull.Value) {
                        bt = obj as byte[];
                    }
                }
            }
            return bt;
        }

        //从数据库直接读取到richTextBox
         public string ReadRtf(string id) {
             byte[] bt = GetBytes(id);
             return System.Text.Encoding.Default.GetString(bt);
         }

使用

            string id = "292450";
            string tmp = @"C:\3.rtf";
            byte[] bt = GetBytes(id);
            File.WriteAllBytes(tmp,bt);
            richTextBox1.LoadFile(tmp);

方法2

从数据库直接读取到richTextBox

//从数据库直接读取到richTextBox
string id = "292440";//abashment
richTextBox1.Rtf = ReadRtf(id);

posted @ 2020-03-26 14:17  XE2011  阅读(578)  评论(0编辑  收藏  举报