Search code examples
c#uwpsd-cardaccess-denied

Access to SD card denied - UWP


Using UWP I'm trying to access an SD card. I'm on Windows 10. I've gone into Package.appxmanifest ...

under Capabilities, I've checked Removable Storage

under Declarations, I've added a File Type Assocation. Name is "txt", File Type is ".txt". The relevant portion ...

  <Extensions>
    <uap:Extension Category="windows.fileTypeAssociation">
      <uap:FileTypeAssociation Name="txt">
        <uap:DisplayName>text</uap:DisplayName>
        <uap:SupportedFileTypes>
          <uap:FileType>.txt</uap:FileType>
        </uap:SupportedFileTypes>
      </uap:FileTypeAssociation>
    </uap:Extension>
  </Extensions>

My code to create a text file ...

    string fileName = @"D:\test.txt";

    using (FileStream fs = File.Create(fileName))
    {   
        Byte[] text = new UTF8Encoding(true).GetBytes("testing");
        fs.Write(text, 0, text.Length);
    }

The result every time, "Access to the path 'D:\text.txt' is denied"

I am able to manually create and copy files to this directory. So, why can I not create a file using UWP? I've followed all the rules. Am I missing something?


Solution

  • You cannot use File.Create() to access files in limited UWP apps. You need to use the functionality in the Windows.Storage namespace.

    private async void Test()
    {
        string filePath = @"D:\";
        string fileName = @"Test.txt";
    
        // get StorageFile object
        StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(filePath);
        StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
    
        // Open Stream and Write content
        using (Stream stream = await file.OpenStreamForWriteAsync())
        {
            Byte[] text = new UTF8Encoding(true).GetBytes("testing");
            await stream.WriteAsync(text, 0, text.Length);
        }
    }