File-related operations in UWP

I recently started to develop UWP, and I copied a part of the code from a previous Winform project to the newly written UWP project. I have sorted out some moths, and I will make a record below.

 

The first point to mention is that the operation of files in UWP should be done with the StorageFile class as much as possible! ! ! ! ! ! ! ! ! ! ! !

 

1. UWP file selection

The file selection of UWP uses FileOpenPicker. I am here to select image files, not to mention the code directly:

            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;
            }

For the specific operations in this area, you can go to Microsoft Dad to check, the most standard and authoritative: https://docs.microsoft.com/zh-cn/windows/uwp/audio-video-camera/imaging

 

 

 

 

 

2. File read operation

This piece of BUG is the most disgusting to me! !

At the beginning, I copied this piece of code directly from the Winform project and used File.ReadAllBytes. As a result, no problem occurred during Debug. After the Release came out, it directly prompted me that I do not have permission to access the file ( UnauthorizedAccessException ) . . . . .

The initial error code (can be used in Winform, if it is in UWP, Release will not run):

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
                        {
                            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;
        }

Then I went to Microsoft Dad to check the File.ReadAllBytes function https://msdn.microsoft.com/en-us/library/system.io.file.readallbytes(v=vs.110).aspx and found the cause of the problem It should be that there is no permission to access the file. After finding the problem, it starts to use the StorageFile method to process the file you have selected. The modified code is as follows:

        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. Other

The operation of changing the properties of the control cannot be written in the asynchronous operation, otherwise it will crash

If there is an operation to read files in the program, try to open the corresponding permissions in the Package.appxmanifest file, although some people can't say it. . . But my head is not iron, I still open honestly.

 

After the problem is solved, I sum up an experience, MSDN is really easy to use! !

  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324637398&siteId=291194637
UWP