none
winrt c# access is denied knownfolders RRS feed

  • Question

  • I am trying to validate the following code in a WinRT project :

    //This is from my MainPage.xaml file
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices.WindowsRuntime;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.Storage;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    
    // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
    
    namespace HelloWorld
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class MainPage : Page
        {
            public object AsynsStatus { get; private set; }
    
            public MainPage()
            {
                WinRTAsyncIntro();
                this.InitializeComponent();
            }
    
            private async void Button_Click(object sender, RoutedEventArgs e)
            {
                MediaElement mediaElement = new MediaElement();
                var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
                Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello World!");
                mediaElement.SetSource(stream, stream.ContentType);
                mediaElement.Play();
            }
            public void WinRTAsyncIntro()
            {
                IAsyncOperation<StorageFile> asyncOp = KnownFolders.MusicLibrary.GetFileAsync("Song.mp3");
                asyncOp.Completed = OpCompleted;
            }
            private void OpCompleted(IAsyncOperation<StorageFile> asyncOp, AsyncStatus status)
            {
                switch (status)
                {
                    case AsyncStatus.Completed:
                        StorageFile file = asyncOp.GetResults(); break;
    
                    case AsyncStatus.Canceled:
                        break;
    
                    case AsyncStatus.Error:
                        Exception exception = asyncOp.ErrorCode; break;
                }
                asyncOp.Close();
            }
        }
    }

    I get an access denied exception. I tried to post an image of the my error in Visual Studio, but have to wait until my account is verified. I also found a link on stackoverflow about it, but the answers did not seem to work for the OP. I can not post the link until my account is verified. 
    Friday, May 3, 2019 9:03 PM

Answers

All replies

  • I guess you need to add a capability to your apps package:
    UWP - File access permissions

    <Capabilities> <rescap:CapabilityName="MusicLibrary"/> </Capabilities>
    • Edited by EckiS Saturday, May 4, 2019 10:38 AM
    Saturday, May 4, 2019 10:38 AM
  • I get a runtime error as follows: 

    "Severity Code Description Project File Line Suppression State
    Error  Validation error. error C00CE169: App manifest validation error: The app manifest must be valid as per schema: Line 32, Column 17, Reason: 'MusicLibrary' violates enumeration constraint of 'internetClient internetClientServer privateNetworkClientServer allJoyn codeGeneration'. The attribute 'Name' with value 'MusicLibrary' failed to parse. HelloWorld C:\Users\usr\source\repos\HelloWorld\HelloWorld\bin\x86\Debug\AppxManifest.xml  "

    Here is a copy of the file with the update you suggested: 

    <?xml version="1.0" encoding="utf-8"?>
    <Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" IgnorableNamespaces="uap mp build" xmlns:build="http://schemas.microsoft.com/developer/appx/2015/build">
      <!--
        THIS PACKAGE MANIFEST FILE IS GENERATED BY THE BUILD PROCESS.
    
        Changes to this file will be lost when it is regenerated. To correct errors in this file, edit the source .appxmanifest file.
    
        For more information on package manifest files, see http://go.microsoft.com/fwlink/?LinkID=241727
      -->
      <Identity Name="a7eb4686-551a-4bd8-b552-e3fb981300da" Publisher="CN=usr" Version="1.0.0.0" ProcessorArchitecture="x86" />
      <mp:PhoneIdentity PhoneProductId="a7eb4686-551a-4bd8-b552-e3fb981300da" PhonePublisherId="00000000-0000-0000-0000-000000000000" />
      <Properties>
        <DisplayName>HelloWorld</DisplayName>
        <PublisherDisplayName>usr</PublisherDisplayName>
        <Logo>Assets\StoreLogo.png</Logo>
      </Properties>
      <Dependencies>
        <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.15063.0" MaxVersionTested="10.0.17763.0" />
      </Dependencies>
      <Resources>
        <Resource Language="EN-US" />
      </Resources>
      <Applications>
        <Application Id="App" Executable="HelloWorld.exe" EntryPoint="HelloWorld.App">
          <uap:VisualElements DisplayName="HelloWorld" Square150x150Logo="Assets\Square150x150Logo.png" Square44x44Logo="Assets\Square44x44Logo.png" Description="HelloWorld" BackgroundColor="transparent">
            <uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png" />
            <uap:SplashScreen Image="Assets\SplashScreen.png" />
          </uap:VisualElements>
        </Application>
      </Applications>
      <Capabilities>
        <Capability Name="MusicLibrary" />
      </Capabilities>
      <Extensions>
        <Extension Category="windows.activatableClass.inProcessServer">
          <InProcessServer>
            <Path>CLRHost.dll</Path>
            <ActivatableClass ActivatableClassId="Microsoft.UI.Xaml.Markup.ReflectionXamlMetadataProvider" ThreadingModel="both" />
          </InProcessServer>
        </Extension>
      </Extensions>
      <build:Metadata>
        <build:Item Name="TargetFrameworkMoniker" Value=".NETCore,Version=v5.0" />
        <build:Item Name="VisualStudio" Version="16.0" />
        <build:Item Name="VisualStudioEdition" Value="Microsoft Visual Studio Community 2019" />
        <build:Item Name="OperatingSystem" Version="10.0.17763.1 (WinBuild.160101.0800)" />
        <build:Item Name="Microsoft.Build.AppxPackage.dll" Version="16.0.28711.60" />
        <build:Item Name="ProjectGUID" Value="{9512344B-4D95-4A88-B418-3407C420D817}" />
        <build:Item Name="OptimizingToolset" Value="None" />
        <build:Item Name="TargetRuntime" Value="Managed" />
        <build:Item Name="Microsoft.Windows.UI.Xaml.Build.Tasks.dll" Version="10.0.17763.132" />
        <build:Item Name="MakePri.exe" Version="10.0.17763.132 (WinBuild.160101.0800)" />
      </build:Metadata>
    </Package>


    I could not add the rescap keyword. 

    I did make some progress however. Apparently Microsoft recommends using folder and filepicker instead so I changed my code, but I get errors at the lines I have labeled below: 

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices.WindowsRuntime;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.Storage;
    using Windows.Storage.Pickers;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Navigation;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    
    // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
    
    namespace HelloWorld
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class MainPage : Page
        {
            public object AsynsStatus { get; private set; }
    
            public MainPage()
            {
                //WinRTAsyncIntro();
                
                this.InitializeComponent();
                
            }
    
            private async void Button_Click(object sender, RoutedEventArgs e)
            {
                MediaElement mediaElement = new MediaElement();
                //PickAFile();
                var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
                Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello World!");
                mediaElement.SetSource(stream, stream.ContentType);
                mediaElement.Play();
                
            }
            public async void PickAFile()
            {
                var picker = new Windows.Storage.Pickers.FileOpenPicker();
                picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
                picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
                picker.FileTypeFilter.Add(".jpg");
                picker.FileTypeFilter.Add(".jpeg");
                picker.FileTypeFilter.Add(".png");
                Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
                if (file != null)
                {
                    this.textBlock.Text = "Picked Photo" + file.Name; //<--Compile time error under textBlcok
    
                }
                else
                {
                    this.textBlock.Text = "Operation cancelled";  //<--Compile time error under textBlcok
                    
                }
            }
            public async void WinRTAsyncIntro()
            {
                IAsyncOperation<StorageFile> asyncOp = KnownFolders.MusicLibrary.GetFileAsync("Song.mp3");
                asyncOp.Completed = OpCompleted;
            }
            private void OpCompleted(IAsyncOperation<StorageFile> asyncOp, AsyncStatus status)
            {
                switch (status)
                {
                    case AsyncStatus.Completed:
                        StorageFile file = asyncOp.GetResults(); break;
    
                    case AsyncStatus.Canceled:
                        break;
    
                    case AsyncStatus.Error:
                        Exception exception = asyncOp.ErrorCode; break;
                }
                asyncOp.Close();
            }
    
            private async void Button_Click_1(object sender, RoutedEventArgs e)
            {
                MediaElement mediaElement = new MediaElement();
                //PickAFile();
                var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
                Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello World!");
                mediaElement.SetSource(stream, stream.ContentType);
                mediaElement.Play();
                var picker = new FileSavePicker();
                picker.SuggestedFileName = "MyFile";
                picker.DefaultFileExtension = ".txt";
                picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                picker.FileTypeChoices.Add("Plaint Text", new List<String> { ".txt" });
                StorageFile file =  await picker.PickSaveFileAsync();
                if (file == null)
                    return;
                await FileIO.WriteTextAsync(file, "...");
                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.ViewMode = PickerViewMode.Thumbnail;
                openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                openPicker.FileTypeFilter.Add(".jpg");
                openPicker.FileTypeFilter.Add(".jpeg");
                openPicker.FileTypeFilter.Add(".png");
                StorageFile file1 = await openPicker.PickSingleFileAsync();
                if (file1 != null)
                {
                    OutputTextBlock.Text = "Picked photo: " + file.Name; //<--Compile time error under Text
                }
                else
                {
                    OutputTextBlock.Text = "Operation Canceled.";   //<--Compile time error under Text
                }
            }
        }
    }
    What do I need to do to add these fields the MainPage object? 


    • Edited by Nu2Csharp Sunday, May 5, 2019 8:38 PM
    Sunday, May 5, 2019 7:58 PM
  • possibly it needs to be: "musicLibrary"
    see App capability declarations
    • Marked as answer by Nu2Csharp Sunday, May 5, 2019 10:42 PM
    Sunday, May 5, 2019 8:31 PM
  • Thanks. I will read it in detail. I am waiting for my account to be verified to post links and pics. I did find a discussion on Stackoverflow about this topic; apparently Microsoft removed access to Documents folder from Visual Studio as of VS 2013, and recommends against editing the xml file. Here are the links I am talking about: 

    http://lunarfrog.com/blog/documents-library-capability-winrt

    https://stackoverflow.com/questions/23681192/how-to-gain-access-to-knownfolders-documentslibrary

    That is why I am trying to use File Picker. 

    Here is what I changed to in my manifest, and I still get access denied error: 

    <Capabilities>
        <Capability Name="internetClient" />
        <Capability Name="musicLibrary"/>
    </Capabilities>

    It is exactly what the docs say I should do.

    Sorry. I stand corrected, it worked when I changed to: 

      <Capabilities>
        <Capability Name="internetClient" />
        <uap:Capability Name="musicLibrary"/>
    </Capabilities>

    Thank you so much.

    • Edited by Nu2Csharp Sunday, May 5, 2019 10:42 PM
    Sunday, May 5, 2019 10:18 PM