5

I have a project where I get the url to a file (e.g. www.documents.com/docName.txt) and I want to create a hash for that file. How can I do this.

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

This is the code i have to create a hash. But seeing how it uses filestream it uses files stored on the hard drive (e.g. c:/documents/docName.txt) But i need it to work with an url to a file and not the path to a file on the drive.

3
  • 2
    It sounds like you're really asking how you get the content associated with a URL... Commented Aug 30, 2013 at 14:33
  • So your question is how to download a file from a URL as a stream so you can hash it? Or is it a locally stored file and you need to resolve its local path? Commented Aug 30, 2013 at 14:33
  • It's a file in SharePoint 2013 and I have an app that sends the url of the document from the app web to the host web where I want to hash it. Commented Aug 30, 2013 at 14:37

2 Answers 2

7

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(); 
Sign up to request clarification or add additional context in comments.

1 Comment

@glautrou Read the body of the question. He wants to download a file and then hash it.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.