How to create SHA256 hash of downloaded text file

泄露秘密 提交于 2019-12-04 09:42:44

To download the file use:

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

using (WebClient client = new WebClient())
{
    client.DownloadFile(url, localPath);
}

then read the file like you have:

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();

You may want to try something like this, although other options may be better depending on the application (and the infrastructure already in place for it) that is actually performing the hashes. Also I am assuming you do not actually want to download and locally store the files.

public static class FileHasher
{
    /// <summary>
    /// Gets a files' contents from the given URI and calculates the SHA256 hash
    /// </summary>
    public static byte[] GetFileHash(Uri FileUri)
    {
        using (var Client = new WebClient())
        {
            return SHA256Managed.Create().ComputeHash(Client.OpenRead(FileUri));
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!