Grusi
Grusi

Reputation: 11

Access to the File System UWP

I have to make a backup of a database through this code which must have access to the File System.

I added the references to the Package.appxmanifest as from this link and I also activated the app permission in the settings.

Settings -> Privacy -> File System and I have activated the app permission. This way you should have access to the files through the paths but it still crashes.

MainPage.xaml.cs:

string constring = "server=localhost;user=user;pwd=password;database=dbtest;";
string file = "C:\\backup.sql";
using (MySqlConnection conn = new MySqlConnection(constring))
{
    using (MySqlCommand cmd = new MySqlCommand())
    {
        using (MySqlBackup mb = new MySqlBackup(cmd))
        {
            cmd.Connection = conn;
            conn.Open();
            mb.ImportFromFile(file);
            conn.Close();
        }
    }
}

Package.appxmanifest:

  xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
  IgnorableNamespaces="uap mp rescap">

  <Capabilities>
    <Capability Name="internetClient" />
    <rescap:Capability Name="broadFileSystemAccess" />
  </Capabilities>

The error is:

Access to the path C:\backup.sql' is denied.

Is there anything I overlook?

Thanks in advance.

Upvotes: 1

Views: 299

Answers (1)

Martin Zikmund
Martin Zikmund

Reputation: 39072

The problem in this case is with the MySqlBackup.ImportFromFile method, which in fact uses System.IO APIs under the hood, which cannot access an arbitrary path even when broadFileSystemAccess is enabled. To be able to access any filesystem path, you need to use the Windows.Storage APIs instead (StorageFile and StorageFolder APIs).

To make it work, you must use other methods MySqlBackup offers - either ImportFromMemoryStream or ImportFromString. For example:

string constring = "server=localhost;user=user;pwd=password;database=dbtest;";
string file = "C:\\backup.sql";
var fileContent = await Windows.Storage.FileIO.ReadTextAsync(file);
using (MySqlConnection conn = new MySqlConnection(constring))
{
    using (MySqlCommand cmd = new MySqlCommand())
    {
        using (MySqlBackup mb = new MySqlBackup(cmd))
        {
            cmd.Connection = conn;
            conn.Open();
            mb.ImportFromString(fileContent);
            conn.Close();
        }
    }
}

Upvotes: 2

Related Questions