【问题标题】:How to access file properly to append text (MD5hash)?如何正确访问文件以附加文本(MD5hash)?
【发布时间】:2014-01-30 10:00:15
【问题描述】:

我正在尝试在文件关闭后附加文件的 MD5 哈希(基于文件的长度)。我是这样做的:

string filePath = "myPath";
string fileName = "myFileName";

File.Delete(filePath + fileName);
if (!File.Exists(filePath + fileName))
{
    using (var sw = File.CreateText(filePath + fileName))
    {
         sw.Write("Stuff to write");
    }
}
using (var sw = File.AppendText(filePath + fileName))
{
    sw.Write(ctx.GetMD5HashFromFile(filePath, fileName));
}

不幸的是,这不起作用,因为文件在两个 using 语句之间没有正确关闭。我收到以下错误:

Unhandled Exception: System.IO.IOException: The process cannot access the file '
[filePath + fileName] because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

如何正确计算 MD5 哈希并附加文本而不会出现异常?

【问题讨论】:

    标签: c# file md5 streamwriter


    【解决方案1】:

    我的猜测是您在第二段代码中打开了两次文件:

    using (var sw = File.AppendText(filePath + fileName))
    {
        sw.Write(ctx.GetMD5HashFromFile(filePath, fileName));
    }
    

    ctx.GetMD5HashFromFile 可能会打开文件来创建哈希;但是您已经打开它来附加数据。所以在 File.AppendText using 块之前创建哈希。

    【讨论】:

      【解决方案2】:

      您没有在创建时关闭文件,请尝试:

      if (!File.Exists(filePath))
      {
            using (var sw = File.CreateText(filePath))
            {
                  sw.Write("Stuff to write");
            }
       }
       FileStream file = File.OpenRead(filePath);
       string hashString = ctx.GetMD5HashFromFile(file);
       file.Close();
      
       File.WriteAllText(filePath, hashString);
      

      获取哈希时只打开文件读取:

      C# calculate MD5 for opened file?

      【讨论】:

      • using 块在退出时关闭流
      • 抱歉,测试错误。新的答案。但巴斯的答案应该是一个
      【解决方案3】:

      我建议使用 Sha1Sum 而不是非常古老且不安全的 MD5

      此函数以“C61211674FD03175FEC87A9C01F39F72376CE104”格式返回值

          public static string MakeSha(string Mystr)
          {
              SHA1CryptoServiceProvider Crpyt = new SHA1CryptoServiceProvider();
              byte[] buf = ASCIIEncoding.ASCII.GetBytes(Mystr);
              return BitConverter.ToString(Crpyt.ComputeHash(buf)).Replace("-", "").ToUpper();
          }
      

      PS:不要忘记在 using 语句中添加以下 using System.Security.Cryptography;

      【讨论】:

      • 这如何回答这个问题?
      • 我会说 Sha1Sum 不太安全。 Sha1Sum 给出 40 字节 MD5 32 字节的结果。破解 40 字节然后 32 字节的代码更难
      • @Bas Brekelmans 我建议使用 Sha1Sum,因为你已经给出了分析器,它更安全!
      • @IsmailGunes 没有人试图破解密码;这用作校验和。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      相关资源
      最近更新 更多