把文件写到数据库

        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public byte[] GetBytes(string fileName)
        {
            FileInfo fi = new FileInfo(fileName);
            FileStream fs = fi.OpenRead();
            byte[] bytes = new byte[fs.Length];
            fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            fs.Dispose();
            return bytes;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="bytes"></param>
        public void CreateNewFile(byte[] bytes)
        {
            FileStream fileStream = new FileStream(@"D:\tes.pdf", System.IO.FileMode.CreateNew);
            fileStream.Write(bytes, 0, bytes.Length);
            fileStream.Close();
        }

 

 

             string connstring = "server=.;database=Test123;uid=;pwd=;";
            string sqltxt = "insert into testpdf([fileName],[fileContentImage],[fileContentbyte]) values(@fileName,@fileContentImage,@fileContentbyte)";

            SqlParameter[] parms = new[]{
                 new SqlParameter("@fileName", SqlDbType.VarChar){Value="123"},
            new SqlParameter("@fileContentbyte", SqlDbType.VarBinary){Value=bytes},
            new SqlParameter("@fileContentImage", SqlDbType.Image){Value=bytes},
            };
            SqlHelper.ExecuteNonQuery(connstring, CommandType.Text, sqltxt, parms);


            //4.从数据库里读取生成文件(.pdf)

            object obj = SqlHelper.ExecuteScalar(connstring, CommandType.Text, "select top 1 fileContentbyte from Testpdf order by addTime desc ");
            byte[] tempBytes = (byte[])obj;
            FileStream fileStream = new FileStream(@"D:\testByte.pdf", System.IO.FileMode.Create);

            fileStream.Write(tempBytes, 0, tempBytes.Length);
            fileStream.Close();

            System.Threading.Thread.Sleep(500);

            object obj1 = SqlHelper.ExecuteScalar(connstring, CommandType.Text, "select top 1 fileContentImage from Testpdf order by addTime desc ");
            byte[] tempBytes1 = (byte[])obj1;
            FileStream fileStream2 = new FileStream(@"D:\testImage.pdf", System.IO.FileMode.Create);

            fileStream2.Write(tempBytes1, 0, tempBytes1.Length);
            fileStream2.Close();

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值