zoukankan      html  css  js  c++  java
  • C#将文件转成16进制码流写入数据库存起来,访问的时候再还原成PDF文件。

    转自https://blog.csdn.net/liubowei_0312/article/details/53378146

    适合将文件写入数据库,远程访问的时候还原
    1.首先把文件转成十六进制文件流
    public void FileToStream()
    {
    try
    {
    IPdfClassBll pdfClassBll = DataFactory.GetPdfClass();
    FileStream fs = new FileStream(@"文件路径/***.PDF", FileMode.Open);
    BinaryReader br = new BinaryReader(fs);
    Byte[] byData = br.ReadBytes((int)fs.Length);
    StringBuilder strResult = new StringBuilder(byData.Length * 8);
    string binary = byteToHexStr(byData);
    PdfInfo pdfinfo = new PdfInfo();
    pdfinfo.PRTNUM = "PH001";//创建的新文件名
    pdfinfo.PDFREPORT = binary;
    pdfClassBll.Add(pdfinfo);
    fs.Close();
    br.Close();
    }
    catch (Exception ex)
    {
    MessageBox.Show("文件写入失败~!");
    }
    }

    /// <summary>
    /// 字节数组转16进制字符串
    /// </summary>
    /// <param name="bytes"></param>
    /// <returns></returns>
    public static string byteToHexStr(byte[] bytes)
    {
    string returnStr = "";
    if (bytes != null)
    {
    for (int i = 0; i < bytes.Length; i++)
    {
    returnStr += bytes[i].ToString("X2");
    }
    }
    return returnStr;
    }

    2.读取数据库中的 PDF流 信息,并写入文件
    =======================

    public void StreamToFile(string prtnum)
    {
    try
    {
    //写入位置
    SampleConfig config = MonitorConfigManager.GetInstance().GetSampleConfig();
    string reportPath = config.ReportPath;
    reportPath = reportPath + "\\" + oSampleInfo.PRTNUM + ".pdf";
    IPdfClassBll pdfClassBll = DataFactory.GetPdfClass();
    PdfInfo pdfInfo = pdfClassBll.GetPdfReportByPRTNUM(prtnum);
    string strPdf = pdfInfo.PDFREPORT;
    byte[] bytes = strToToHexByte(strPdf);
    FileStream fileStream = new FileStream(reportPath, FileMode.OpenOrCreate, FileAccess.Write);
    fileStream.Write(bytes, 0, bytes.Length);
    BinaryWriter binaryWriter = new BinaryWriter(fileStream);
    binaryWriter.Write(bytes);
    binaryWriter.Close();
    fileStream.Close();
    }
    catch (Exception ex)
    {

    }
    }
    /// <summary>
    /// 16进制字符串转为文字
    /// </summary>
    /// <param name="hexString"></param>
    /// <returns></returns>
    private static byte[] strToToHexByte(string hexString)
    {
    hexString = hexString.Replace(" ", "");
    if ((hexString.Length % 2) != 0)
    hexString += " ";
    byte[] returnBytes = new byte[hexString.Length / 2];
    for (int i = 0; i < returnBytes.Length; i++)
    returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);

    return returnBytes;
    }

  • 相关阅读:
    8小时外你做什么?下班后的生活决定你的竞争力
    8个月,一位年轻总裁的坠落:值得所有职业经理人深思
    陈紫熹(帮别人名字作诗)
    年轻人创业尤其要注意的五个基本法则
    解密联想20年的45条法则
    小本创业】30条生意妙经及七大关键感悟
    新时代白领必备的两大“新”能力,你有吗?
    秘笈:送给创业者的19条忠告
    C#计算两个日期之间的差
    tnsnames.ora是什么东东?
  • 原文地址:https://www.cnblogs.com/chinayixia/p/12513479.html
Copyright © 2011-2022 走看看