如何创建下载文本文件的SHA256哈希

我有一个项目,我得到一个文件的URL(例如www.documents.com/docName.txt),我想为该文件创建一个哈希。 我怎样才能做到这一点。

FileStream filestream; SHA256 mySHA256 = SHA256Managed.Create(); filestream = new FileStream(docUrl, FileMode.Open); filestream.Position = 0; byte[] hashValue = mySHA256.ComputeHash(filestream); Label2.Text = BitConverter.ToString(hashValue).Replace("-", String.Empty); filestream.Close(); 

这是我必须创建哈希的代码。 但是看看它如何使用文件流它使用存储在硬盘驱动器上的文件(例如c:/documents/docName.txt)但是我需要它来处理文件的URL而不是驱动器上文件的路径。

要下载文件,请使用:

 string url = "http://www.documents.com/docName.txt"; string localPath = @"C://Local//docName.txt" using (WebClient client = new WebClient()) { client.DownloadFile(url, localPath); } 

然后像你一样阅读文件:

 FileStream filestream; SHA256 mySHA256 = SHA256Managed.Create(); filestream = new FileStream(localPath, FileMode.Open); filestream.Position = 0; byte[] hashValue = mySHA256.ComputeHash(filestream); Label2.Text = BitConverter.ToString(hashValue).Replace("-", String.Empty); filestream.Close(); 

您可能想尝试这样的事情,尽管其他选项可能会更好,具体取决于实际执行哈希的应用程序(以及已经存在的基础结构)。 另外我假设你实际上并不想下载和本地存储文件。

 public static class FileHasher { ///  /// Gets a files' contents from the given URI and calculates the SHA256 hash ///  public static byte[] GetFileHash(Uri FileUri) { using (var Client = new WebClient()) { return SHA256Managed.Create().ComputeHash(Client.OpenRead(FileUri)); } } }