读取结束缺少字符 c#



>我有一个XML文件,其中包含有关使用此方法解密的stringConnection参数的信息:

public void DecryptFile(string sInputFileName, string sOutputFileName, string sKey)
{
    DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
    DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
    DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
    FileStream fsread = new FileStream(sInputFileName, FileMode.Open, FileAccess.Read);
    ICryptoTransform desdecrypt = DES.CreateDecryptor();
    CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);
    //Print result
    StreamWriter fsDecrypted = new StreamWriter(sOutputFileName);
    //In this point ReadToEnd return the final xml result decrypted
    fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
    fsDecrypted.Flush();
    fsDecrypted.Close();
    fsread.Close();
    fsread.Dispose();
}

结果将是这样的:

<?xml version="1.0" standalone="yes"?>
<NewDataSet>
  <TU>
    <BD>DataBaseName</BD>
    <SR>ServerName</SR>
    <USR>UserDB</USR>
    <CONT>Pass</CONT>
    <EMP>codCompany</EMP>
    <EMPDES>companyName</EMPDES>
    <SUC>codLocal</SUC>
  </TU>
</NewDataSet>

但是ReadToEnd不会返回我的 XML 文件的最后一个标签,如下所示:

<?xml version="1.0" standalone="yes"?>
<NewDataSet>
  <TU>
    <BD>DataBaseName</BD>
    <SR>ServerName</SR>
    <USR>UserDB</USR>
    <CONT>Pass</CONT>
    <EMP>codCompany</EMP>
    <EMPDES>companyName</EMPDES>
    <SUC>codLocal</SUC>
  </TU>
</NewDataSet

我的方法有什么问题?

主要问题是你并没有真正阅读CryptoStream到最后,因为它阻塞数据的方式(如本答案所示(。这是根据此答案改编的方法,该方法使用缓冲区一次读取 1024 个字节。

public void DecryptFile(string sInputFileName, string sOutputFileName, string sKey)
{
    DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
    DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
    DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
    ICryptoTransform desdecrypt = DES.CreateDecryptor();
    using (FileStream fsread = new FileStream(sInputFileName, FileMode.Open, FileAccess.Read))
    using (StreamWriter fsDecrypted = new StreamWriter(sOutputFileName))
    using (CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read))
    {
        //Print result
        var buffer = new byte[1024];
        var read = cryptostreamDecr.Read(buffer, 0, buffer.Length);
        while (read > 0)
        {
            fsDecrypted.Write(buffer, 0, read);
            read = cryptostreamDecr.Read(buffer, 0, buffer.Length);
        }
    }
}

您还缺少using语句,这些语句可确保正确处理流,无论程序是否有异常。

相关内容

  • 没有找到相关文章

最新更新