UWP中的文件相關操作


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

 

首先提一個重點就是:UWP里關於文件的操作盡量用StorageFile類來搞!!!!!!!!!!!!

 

1.UWP的文件選取

UWP的文件選取使用的是FileOpenPicker,我這里是用來選圖片文件的,不多說直接上代碼:

            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/imaging

 

 

 

 

 

2.文件讀取操作

這一塊兒的BUG是最讓我惡心的!!

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

最初的錯誤代碼(可以在Winform里面用,UWP里面的話Release出來跑不成):

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的方法來處理自己所選擇的文件修改后的代碼如下:

        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真好用!!

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM