• C# IO流的操作(二)


    文件在操作系统中是以二进制(01)的形式保存到磁盘上的,在C#程序当中,我们可以通过读取流将文件读取到byte[]当中(读到内存中),也可以通过写入流将byte[]写入文件(保存到磁盘上)。下面将演示一例文件与数据库结合的示例——将文件保存到数据库,再从数据库还原为文件。

    写入文件到数据库部分代码:

     /// <summary>
     /// 写入按钮事件
     /// </summary>
     private void button1_Click(object sender, EventArgs e)
     {
         //将文件读取到字节数组
         FileStream fs = new FileStream("test.docx", FileMode.Open);
         byte[] bytes = new byte[(int)fs.Length];
         fs.Read(bytes, 0, bytes.Length);
    
         //保存到数据库
         using (SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=123456;database=test"))
         {
             conn.Open();
             string sql = "insert into 文件表([file]) values(@file)";
             SqlCommand cmd = new SqlCommand(sql, conn);
             cmd.Parameters.Add(new SqlParameter("@file", bytes));
             int i = cmd.ExecuteNonQuery();
             if (i > 0)
             {
                 MessageBox.Show("文件写入成功");
             }
         }
     }

    读取数据库byte[]到本地磁盘文件的代码:

    /// <summary>
    /// 读取按钮事件
    /// </summary>
    private void button2_Click(object sender, EventArgs e)
    {
        using (SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=123456;database=test"))
        {
            conn.Open();
            string sql = "select [file] from 文件表";
            SqlCommand cmd = new SqlCommand(sql, conn);
    
            SqlDataReader sdr = cmd.ExecuteReader();
            if (sdr.Read())
            {
                byte[] bytes = (byte[])sdr["file"];
    
                //直接写入字节数组到文件(写法1)
                File.WriteAllBytes("test-new.docx", bytes);
                MessageBox.Show("文件保存成功");
    
                //将字节数组读取到流,然后用流写入文件(写法2)
                FileInfo file = new FileInfo("test-new.docx");
                FileStream fs = file.OpenWrite();
                fs.Write(bytes, 0, bytes.Length);
                fs.Close();
    
                //将字节数组写入内存流,直接从内存流中加载图片显示
                MemoryStream ms = new MemoryStream();
                ms.Write(bytes, 0, bytes.Length);
                this.pictureBox1.Image = Image.FromStream(ms);
            }
            sdr.Close();
        }
    }

    说明:

    1)数据库file字段是sql关键字,所以用[]括号括起来[file]。此外file字段要设置为image类型。

    2)上述的代码部分演示了保存本地word文件到数据库,再从数据库还原为word文档的过程,对于图片(包括gif动画)也是一样的操作方式。

  • 相关阅读:
    【BZOJ2227】【ZJOI2011】看电影 [组合数][质因数分解]
    【BZOJ2648】SJY摆棋子 [KD-tree]
    【BZOJ3237】【AHOI2013】连通图 [CDQ分治]
    【BZOJ1901】Dynamic Rankings [整体二分]
    【BZOJ2527】【POI2011】Meteors [整体二分]
    【BZOJ3624】【APIO2008】免费道路 [生成树][贪心]
    【BZOJ2663】灵魂宝石 [二分]
    【BZOJ4653】【NOI2016】区间 [线段树]
    【BZOJ2049】【SDOI2008】洞穴勘测 [LCT]
    【BZOJ4008】【HNOI2015】亚瑟王 [期望DP]
  • 原文地址:https://www.cnblogs.com/guwei4037/p/8074470.html
Copyright © 2020-2023  润新知