簡體   English   中英

從目錄獲取字節數組

[英]Get byte array from directory

我正在制作一個小的工具來獲取文件或目錄的哈希值以查看校驗和。 現在,它顯示單個文件的哈希,但是當我嘗試獲取整個目錄時,出現錯誤System.UnauthorizedAccessException: 'Access to the path 'D:\\dev\\hashcheck' is denied.'

這是代碼的簡化版本,僅因為其重復性很強而得以簡化。

byte[] fileByte = File.ReadAllBytes(path); //This is where the error is
MD5 md5Hash = MD5.Create();        
Console.WriteLine("The MD5 Hash of the file is; " + 
                  BitConverter.ToString(md5Hash.ComputeHash(fileByte))
                              .Replace("-", string.Empty)
                              .ToLower());

我嘗試將<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />到應用程序清單中。

根據ReadAllBytes文檔 ,第一個參數是:

路徑。 字符串要讀取的文件。

因此,您必須提供文件的路徑,而不是其他任何文件的路徑。 目錄當然不是文件,因此它將無法正常工作。

我不確定您所說的“目錄哈希”是什么意思,但是在我看來,您可能需要打開單個文件(以確定的順序),連接它們的字節,然后在整個過程中運行哈希算法,即生成包含整個文件集的虛擬字節流。

var virtualByteStream = Directory
    .GetFiles(path)
    .OrderBy( p => p )
    .SelectMany
    (
        p => p.ReadAllbytes()
    );
var hash = md5Hash.ComputeHash(virtualByteStream.ToArray());

請注意,此方法不包括文件元數據(例如DateModified),因此,如果這對您很重要,則需要在散列輸入中包括它以及任何其他元數據。

(如果文件很大,則可能希望找到一種避免ToArray()調用的方法,而改用ComputeHash(Stream) 。但這超出了此答案的范圍。)

您需要先獲取目錄中的所有文件,然后才能讀取內容,如下所示:

using System.IO;


        foreach (string file in Directory.GetFiles(path))
        {
            byte[] fileByte = File.ReadAllBytes(file);
            MD5 md5Hash = MD5.Create();        
            Console.WriteLine("The MD5 Hash of the file is; " + 
                  BitConverter.ToString(md5Hash.ComputeHash(fileByte))
                              .Replace("-", string.Empty)
                              .ToLower());        
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM