2012-01-17 19 views
0

我需要在經常更改的文件上計算SHA1。我可以在Windows資源管理器中複製,粘貼,打開存檔文件,但是我在using指令中遇到了UnauthorizedAccessException異常。表明我有一個只讀文件,該文件在文件的屬性中似乎不是真的。可以複製粘貼,在Windows資源管理器中打開存檔但無法從代碼讀取?

存檔位於我有權訪問的位置的共享驅動器上。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 
using System.Security.Cryptography; 

namespace TheTest 
{ 
    public class MakeSha1 
    { 
     static void Main(string[] args) 
     { 
      using (FileStream fs = new FileStream(@"###.xml.gz", FileMode.Open)) 
      { 
       using (SHA1Managed sha1 = new SHA1Managed()) 
       { 
        byte[] hash = sha1.ComputeHash(fs); 
        StringBuilder formatted = new StringBuilder(hash.Length); 
        foreach (byte b in hash) 
        { 
         formatted.AppendFormat("{0:X2}", b); 
        } 
        Console.WriteLine(formatted.ToString()); 
       } 
       Console.ReadKey(); 
      } 
     } 
    } 
} 
+0

如果您提到異常,至少包括消息。 – Reniuz 2012-01-17 09:16:05

回答

2

您正在使用FileStream沒有明確指定文件共享的構造函數,所以沒有文件共享是默認允許的。如果文件被頻繁修改,那麼你可能會使用不同形式的構造函數會更好:

using (fs = new FileStream(@"###.xml.gz", FileMode.Open, 
          FileAccess.Read, FileShare.ReadWrite) 
{ 
    // ... your code here 
} 

注意,如果另一個進程修改,而你正在處理的文件,那麼你的SHA1將不準確。

+0

不錯,添加了FileAccess.Read的技巧;) – Jerome 2012-01-17 09:23:36

+0

+1因爲你有一個熊貓作爲頭像:p – 2012-01-17 10:18:15

相關問題