首页 > 解决方案 > C#读取文本文件,在内存中压缩,在检索时存储到SQL Db,它的开头和结尾都有垃圾字符

问题描述

我将压缩文件存储在 sql Db 中。我的问题是我的输出文件开头有垃圾'ÿÿÿÿà'和结尾有''。也许是编码问题?我不确定该怎么办。下面是我的代码,也许你能纠正它?

下面是解压后发送到记事本后从数据库输出的文件:

ÿÿÿÿ à RQHR~OOPBILL~P ~P-WDM~11/06/2018~A0000000000 ~HE,NE ~17/06/1970 ~F ~P8111235 ~AITO, HARMONIE ~GLUFA~LABEL~A1CHB~PRENA~LIPID~TSHFU~ FRT4 ~U/A ~MA/C ~EGFR1~UMICU~ ~ ~ ~ ~ ~ ~ ~ ~ eol RQHR~OOPBILL~C1~NIPMC~13/06/2018~A1111111111 ~ZEN,DA ~04/04/1928 ~ M ~P8132387 ~EKE, NKEMAKOLAM ~A1CHB~LABEL~MA/C ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~eol

我不确定意外字符是在读取时出现还是出现在输出中。我已经阅读了有关“BOM”的信息,也许这是相关的?

这是我的输入代码:

byte[] compressedFile=null;
Int64 FileSize;

// Save the orig text file into the Db
if (bSaveFile)
{
    Encoding utf8WithoutBom = new UTF8Encoding(false);
    byte[] data = System.IO.File.ReadAllBytes(FileName);
    FileSize = data.Length;

    byte[] compressedData =Util.Compress(data);

    compressedFile = compressedData;
}

然后将 CompressedFile 存储到数据库中。

这是我的阅读代码:

public string OpenFile(string FileGUID)
{
    logger.Trace("Entered");

    Byte[] data = new byte[0] ;
    System.Data.DataTable oDt = new System.Data.DataTable();
    string Sql = "Select RefFile FROM FileDetails Where FileGID = '" + FileGUID + "'";

    SqlDataAdapter Da = new SqlDataAdapter(Sql, _SqlConnection);
    Da.Fill(oDt);
    if (oDt.Rows.Count > 0)
        data = (Byte[]) ( oDt.Rows[0]["RefFile"]);

    data = Util.Decompress(data);
    string tPath =  System.IO.Path.GetTempFileName();

    using (FileStream fs = File.Create(tPath, 2048, FileOptions.None))
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(fs, data);
    }
    return tPath;
}

这些是它使用的压缩例程:

public static byte[] Compress(byte[] data)
{
    var output = new MemoryStream();
    using (var gzip = new System.IO.Compression.GZipStream(output, CompressionMode.Compress, true))
    {
        gzip.Write(data, 0, data.Length);
        gzip.Close();
    }
    return output.ToArray();
}

public static byte[] Decompress(byte[] data)
{
    var output = new MemoryStream();
    var input = new MemoryStream();
    input.Write(data, 0, data.Length);
    input.Position = 0;

    using (var gzip = new GZipStream(input, CompressionMode.Decompress, true))
    {
        var buff = new byte[64];
        var read = gzip.Read(buff, 0, buff.Length);

        while (read > 0)
        {
            output.Write(buff, 0, read);
            read = gzip.Read(buff, 0, buff.Length);
            }
        gzip.Close();
    }
    return output.ToArray();
}

标签: c#.net

解决方案


您不需要此代码:

using (FileStream fs = File.Create(tPath, 2048, FileOptions.None))
{
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(fs, data);
}

BinaryFormatter添加序列化元数据。将所有这些代码替换为:

File.WriteAllBytes(tPath, data);

推荐阅读