winrt获取文件MD5码

//小文件

public static string ComputeMD5(byte[] bytes)

        {

            var alg = HashAlgorithmProvider.OpenAlgorithm("MD5");

            IBuffer buff = CryptographicBuffer.CreateFromByteArray(bytes);

            var hashed = alg.HashData(buff);

            var res = CryptographicBuffer.EncodeToHexString(hashed);

            return res;

        }

        public static byte[] StreamToBytes(Stream stream)

        {

            byte[] bytes = new byte[stream.Length];//这个地方会报内存不够,文件太大了

            stream.Read(bytes, 0, bytes.Length);

            return bytes;

        }

//大文件的话必须用数据流,不然会内存不够,一般大于50M的最好用流的形式比较好

        public static async Task<string> ComputeMD5(Stream stream)

        {

            var alg = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);

            var inputStream = stream.AsInputStream();

            const uint capacity = 1000000000;//100M这个参数可以自己修改,根据自己的配置决定

            var buffer = new Windows.Storage.Streams.Buffer(capacity);

            var hash = alg.CreateHash();





            while (true)

            {

                await inputStream.ReadAsync(buffer, capacity, InputStreamOptions.None);

                if (buffer.Length > 0)

                    hash.Append(buffer);

                else

                    break;

            }

            string hashText = CryptographicBuffer.EncodeToHexString(hash.GetValueAndReset()).ToLower();

            

            return hashText;

        }

使用例子:
StorageFile MYFile = await KnownFolders.DocumentsLibrary.GetFileAsync("791d5b3b142c6ba114eecc12ac2ff751.mp4");
            Stream mystream = (await MYFile.OpenAsync(FileAccessMode.Read)).AsStream();
            string txt2 = ComputeMD5(StreamToBytes(mystream));//使用正常获取,可能报错
            string txt = await ComputeMD5(mystream);//使用流方式获取

 

你可能感兴趣的:(MD5)