2017-08-04 36 views
1

我使用一个可以服务将文件上传到Azure存储服务,所以我想用MD5校验来检查文件的完整性,所以首先我得到函数的校验和。Azure中存储的文件有不同的MD5校验比本地文件(即同一个文件)

public static string GetMD5HashFromFile(Stream stream) 
{ 
    using (var md5 = MD5.Create()) 
    { 
     return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", string.Empty); 
    } 
} 

为我用我得到的测试文件:1dffc245282f4e0a45a9584fe90f12f2,我得到了相同的结果,当我使用像this一个在线工具。

然后我将文件上传到Azure和从我的代码是这样得到它:(为了避免包括验证假设的文件和目录确实存在。)

public bool CompareCheckSum(string fileName, string checksum) 
{ 
    this.storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("MyConnectionString")); 
    this.fileClient = this.storageAccount.CreateCloudFileClient(); 
    this.shareReference = this.fileClient.GetShareReference(CloudStorageFileShareSettings.StorageFileShareName); 
    this.rootDir = this.shareReference.GetRootDirectoryReference(); 
    this.directoryReference = this.rootDir.GetDirectoryReference("MyDirectory"); 
    this.fileReference = this.directoryReference.GetFileReference(fileName); 

    Stream stream = new MemoryStream(); 
    this.fileReference.DownloadToStream(stream); 
    string azureFileCheckSum = GetMD5HashFromFile(stream); 

    return azureFileCheckSum.ToLower() == checksum.ToLower(); 
} 

我还尝试了使用不同的过程是这样的校验:

public bool CompareCheckSum(string fileName, string checksum) 
{ 
    this.storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("MyConnectionString")); 
    this.fileClient = this.storageAccount.CreateCloudFileClient(); 
    this.shareReference = this.fileClient.GetShareReference(CloudStorageFileShareSettings.StorageFileShareName); 
    this.rootDir = this.shareReference.GetRootDirectoryReference(); 
    this.directoryReference = 
    this.rootDir.GetDirectoryReference("MyDirectory"); 
    this.fileReference = this.directoryReference.GetFileReference(fileName); 

    this.fileReference.FetchAttributes(); 
    string azureFileCheckSum = this.fileReference.Metadata["md5B64"]; 

    return azureFileCheckSum.ToLower() == checksum.ToLower(); 
} 

最后,对于azureFileCheckSum我越来越:d41d8cd98f00b204e9800998ecf8427e不知道我做错了什么,或者什么变化,当我将文件上传到FTP ...

回答

2

在您致电md5.ComputeHash(stream)之前,您需要将流的位置重置为开头。

stream.Position = 0; 

当然,这将失败,NotSupportedException如果流类型不支持查找,但在你的情况下,它应该工作。

+0

太棒了!它的工作,非常感谢! –

+0

专业提示:'d41d8cd98f00b204e9800998ecf8427e'是零个字节的MD5哈希值,所以很容易被发现。 –

相关问题