2013-08-30 50 views
4

我有一個項目,我得到的URL到一個文件(例如www.documents.com/docName.txt),我想爲該文件創建一個哈希。我怎樣才能做到這一點。如何創建下載的文本文件SHA256哈希

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到文件而不是驅動器上的文件的路徑。

+2

這聽起來像你真的* *問你如何得到與URL相關聯的內容...... –

+0

所以你的問題是如何從一個URL下載文件流,所以你可以散列嗎?或者它是一個本地存儲的文件,你需要解析它的本地路徑? – Alex

+0

這是SharePoint 2013中的一個文件,我有一個應用程序將文檔的URL從應用程序網站發送到主機網站,並在其中對其進行散列。 – Marijn

回答

4

要下載文件的使用:

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

@glautrou閱讀問題的主體。他想要下載一個文件然後對其進行哈希處理。 –

1

你可能想嘗試這樣的事情,雖然其他選擇可能更取決於應用程序(以及已有的基礎架構)實際上正在執行哈希。另外,我假設你實際上並不想下載和本地存儲文件。

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