Karel_cz
Karel_cz

Reputation: 133

File access denied in C# uwp

I am solving one issue. I am developing uwp app and I need to get sha256 hash of file selected with filepicker. I have complete part with filepicker, but when I select file from my computer with filepicker and I want to check hash of this file, I get error message about access denied. Did anyone solved such a problem? I thought, that when I select file with filepicker, I can access it, right?

Upvotes: 1

Views: 1546

Answers (1)

Karel_cz
Karel_cz

Reputation: 133

Solved. I problem was with init of stream, I inited a new stream by name, but it doesnt work this way. I found, that if I go throught all files selected with filepicker, I would use object returned from filepicker. Working example:

        var picker = new Windows.Storage.Pickers.FileOpenPicker();
        picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
        picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
        picker.FileTypeFilter.Add(".avi");
        picker.FileTypeFilter.Add(".mp4");
        picker.FileTypeFilter.Add(".mpeg");
        picker.FileTypeFilter.Add(".mov");
        picker.FileTypeFilter.Add(".mkv");

        IReadOnlyList<StorageFile> files = await picker.PickMultipleFilesAsync();
        if (files.Count > 0)
        {
            // doing some needed staff

            StringBuilder output = new StringBuilder("Picked files:\n\n");

            // Application now has read/write access to the picked file(s)
            foreach (StorageFile file in files)
            {
                output.Append(file.Name + "\n");

                using (IRandomAccessStream filestream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    output.Append("File SHA256 hash -> " + BytesToString(Sha256.ComputeHash(filestream.AsStreamForRead())) + "\n\n");
                    await filestream.FlushAsync();
                }
            }
            this.filePickerInfo.Text = output.ToString();                
        }
        else
        {
            this.filePickerInfo.Text = "Operation cancelled.";                
        }    

Upvotes: 3

Related Questions