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

Mar*_*ijn 4 c# hash filestream

我有一个项目,我获取文件的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();
Run Code Online (Sandbox Code Playgroud)

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

Sam*_*ach 6

要下载文件,请使用:

string url = "http://www.documents.com/docName.txt";
string localPath = @"C://Local//docName.txt"

using (WebClient client = new WebClient())
{
    client.DownloadFile(url, localPath);
}
Run Code Online (Sandbox Code Playgroud)

然后像你一样阅读文件:

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();
Run Code Online (Sandbox Code Playgroud)