“System.UnauthorizedAccessException: Access to the path is denied” when accessing file path in MAUI app

I’m trying to add the zip file (contains .s3db file) in my .NET 7 MAUI app.
I am able to create a directory. But, when I try to delete the file or use File.WriteAllBytes(), it throws “Access to the path is denied”.

I have tried both System.Environment and FileSystem.Current.AppDataDirectory to access the directory.

ZipDBPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "TempSD", "StaticData.zip")

ZipDBPathDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "TempSD");

if (data != null && data.Length > 0)
{
    File.Delete(App.ZipDBPath);
    Directory.CreateDirectory(App.ZipDBPath);
    File.WriteAllBytes(App.ZipDBPath, data);
    ZipFile.ExtractToDirectory(App.ZipDBPath, App.ZipDBPathDir);
    File.Delete(App.ZipDBPath);
}

NOTE: I also have the same code block in xamarin.forms project and it is Working fine.

  • Are you sure the folder exists? You are using the full file path when calling CreateDirectory

    – 

  • You can skip the first line File.Delete(App.ZipDBPath);. Second line creates a new zip file with 0kb. Third line line throws the Error.

    – 

  • according to the docs, CreateDirectory should throw an exception if it is given a file path. I’d try calling it with just the folder path to see if that makes any difference.

    – 

Leave a Comment