Win8 文件相关操作

1.文件选择
var openPicker = new FileOpenPicker
                {
                    ViewMode = PickerViewMode.Thumbnail,
                    SuggestedStartLocation = PickerLocationId.ComputerFolder
                };
                openPicker.FileTypeFilter.Add("*");


                StorageFile file = await openPicker.PickSingleFileAsync();

2.获取文件大小
  BasicProperties pro = await file.GetBasicPropertiesAsync();
                UInt64 size = pro.Size;

3.convert StorageFile to byte[]
  1. var bytes = await GetBtyeFromFile(file);  
  2.   
  3. // This is the method to convert the StorageFile to a Byte[]          
  4. private async Task GetBtyeFromFile(StorageFile storageFile)  
  5. {  
  6.     var stream = await storageFile.OpenReadAsync();  
  7.   
  8.     using (var dataReader = new DataReader(stream))  
  9.     {  
  10.         var bytes = new byte[stream.Size];  
  11.         await dataReader.LoadAsync((uint)stream.Size);  
  12.         dataReader.ReadBytes(bytes);  
  13.   
  14.         return bytes;  
  15.     }  
  16. }  

4.convert the Byte[] to an Image
  1. var stream = new MemoryStream(bytes);  
  2.             var randomAccessStream = new MemoryRandomAccessStream(stream);  
  3.   
  4.             var bi = new BitmapImage();  
  5.             bi.ImageFailed += (s, o) =>  
  6.             {  
  7.         // This event is optional and is used to let us know if something went wrong  
  8.                 var m = "Failure;  
  9.             };  
  10.   
  11.             bi.SetSource(randomAccessStream);  
5.获取文件MD5
private async Task<string> GetMd5(StorageFile file)
        {
            HashAlgorithmProvider alg = Windows.Security.Cryptography.Core.HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            var stream = await file.OpenStreamForReadAsync();
            var inputStream = stream.AsInputStream();
            const uint capacity = 100000000;
            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()).ToUpper();


            inputStream.Dispose();
            stream.Dispose();
            return hashText;
        }

6. 生成GUID

1、Guid.NewGuid().ToString("N") 结果为:
      38bddf48f43c48588e0d78761eaa1ce6

2、Guid.NewGuid().ToString("D") 结果为: 
      57d99d89-caab-482a-a0e9-a0a803eed3ba

3、Guid.NewGuid().ToString("B") 结果为:
     {09f140d5-af72-44ba-a763-c861304b46f8}

4、Guid.NewGuid().ToString("P") 结果为:
     (778406c2-efff-4262-ab03-70a77d09c2b5)

默认第2种效果

Win8 文件相关操作

上一篇:[转]JavaSE 8—新的时间和日期API


下一篇:Jenkins 持续集成环境搭建