UWP中的文件相關操做

最近開始作UWP開發,圖省事兒就把本身以前一個Winform項目的一部分代碼拷貝到了新寫的UWP項目中來。整出了一些幺蛾子,下面作一個記錄。windows

 

首先提一個重點就是:UWP裏關於文件的操做盡可能用StorageFile類來搞!!!!!!!!!!!!app

 

1.UWP的文件選取異步

UWP的文件選取使用的是FileOpenPicker,我這裏是用來選圖片文件的,很少說直接上代碼:async

            FileOpenPicker fileOpenPicker = new FileOpenPicker();
            fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            fileOpenPicker.FileTypeFilter.Add(".jpg");
            fileOpenPicker.FileTypeFilter.Add(".png");
            fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;

            var imgFile = await fileOpenPicker.PickSingleFileAsync();

            if (imgFile == null)
            {
                return;
            }

關於這塊兒的具體的各類操做能夠去微軟爸爸那裏查,最標準最權威:https://docs.microsoft.com/zh-cn/windows/uwp/audio-video-camera/imagingide

 

 

 

 

 

2.文件讀取操做函數

這一起的BUG是最讓我噁心的!!this

最開始的時候這一起的代碼我是直接從Winform項目裏直接拷出來的用的是File.ReadAllBytes,結果Debug的時候什麼問題都沒有出現,Release出來後直接提示我沒有權限訪問文件(UnauthorizedAccessException)。。。。。spa

最初的錯誤代碼(能夠在Winform裏面用,UWP裏面的話Release出來跑不成):code

private async Task<List<ByteArrayContent>> GetFileByteArrayContent(HashSet<string> files)
        {
            List<ByteArrayContent> list = new List<ByteArrayContent>();
           
            foreach (var file in files)
            {
                await Task.Run(() => {
                    if(file.Length > 0)
                    {
                        try
                        {
                            //file是string類型的文件路徑
                            var fileContent = new ByteArrayContent(File.ReadAllBytes(file));
                            ContentDispositionHeaderValue dispositionHeader = new ContentDispositionHeaderValue("file");
                            dispositionHeader.DispositionType = "file";
                            dispositionHeader.Name = "imageFile";
                            dispositionHeader.FileName = Path.GetFileName(file);
                            fileContent.Headers.ContentDisposition = dispositionHeader;
                            list.Add(fileContent);
                        }
                        catch(Exception ex)
                        {
                            this.TextBlock_lyric.Text = ex.Message;
                        }
                    }
                });
            }
            return list;
        }

 

而後我去微軟爸爸那兒裏查了一下File.ReadAllBytes函數https://msdn.microsoft.com/en-us/library/system.io.file.readallbytes(v=vs.110).aspx以後發現問題緣由應該是沒有權限訪問文件,查到問題所在後就開始用StorageFile的方法來處理本身所選擇的文件修改後的代碼以下:orm

        private async Task<List<ByteArrayContent>> GetByteArrayContents()
        {
            List<ByteArrayContent> files = new List<ByteArrayContent>();
            string exceptionMsg = string.Empty;
            if (imgFile != null)
            {
                try
                {
                    //imgFile是一個StorageFile類的對象
                    var buffer = await FileIO.ReadBufferAsync(imgFile);
                    byte[] content = new byte[buffer.Length];
                    // Use a dataReader object to read from the buffer
                    using (DataReader dataReader = DataReader.FromBuffer(buffer))
                    {
                        dataReader.ReadBytes(content);
                        // Perform additional tasks
                    }

                    var fileContent = new ByteArrayContent(content);
                    ContentDispositionHeaderValue dispositionHeader = new ContentDispositionHeaderValue("file");
                    dispositionHeader.DispositionType = "file";
                    dispositionHeader.Name = "imageFile";
                    dispositionHeader.FileName = imgFile.Path;
                    fileContent.Headers.ContentDisposition = dispositionHeader;
                    files.Add(fileContent);
                }
                catch (Exception ex)
                {
                    exceptionMsg = ex.Message;
                }
            }
            this.TextBlock_lyric.Text += exceptionMsg;
            return files;
        }

 

3.其餘

更改控件屬性的操做不能寫到異步操做裏,否則會崩

程序裏有讀取文件的操做的話儘可能去把Package.appxmanifest文件裏對應的權限開一下,雖然有的人說不開也行。。。可是我頭不鐵,我仍是老老實實開了。

 

問題解決後總結出一條經驗,MSDN真好用!!

相關文章
相關標籤/搜索