Uploads folder in wwwroot doesn't have access to delete a file by the app

John Mangam 0 Reputation points
2024-11-19T08:58:06.28+00:00

Hi,

I have an Uploads folder in an App Service and uploading is successful.

However, when the app tries to delete the uploaded files, it encounters the error: **System.IO.IOException: Invalid access to memory location. : 'C:\home\site\wwwroot\wwwroot\sample\uploads\MyFile.txt'
**
I see the structure to be: myapp.scm.azurewebsites.net/dev/wwwroot/wwwroot/sample/uploads/MyFile.txt

private readonly string myUploadFolderPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", configuration["mySettings:UploadsFolderPath"]);

public bool RemoveUploadedFiles()
{
  if (Directory.Exists(myUploadFolderPath))
 {
    string[] files = Directory.GetFiles(myUploadFolderPath);

    foreach (string file in files)
    {
        File.Delete(file);
    }
    return true;
 }
 return false;
}

Thank you.

Best regards,
John

Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
7,951 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Shree Hima Bindu Maganti 730 Reputation points Microsoft Vendor
    2024-11-21T07:04:11.6233333+00:00

    Hi John Mangam ,

    Welcome to the Microsoft Q&A Platform!
    The issue you're encountering with file deletion in an Azure App Service is due to the incorrect path being used for accessing the files. From the error message and the file path structure you've shared, it appears that the app is trying to access the files in an invalid directory
    (C:\home\site\wwwroot\wwwroot\sample\uploads), .

    Fix Path Construction: Remove the redundant wwwroot from the path:

    private readonly string myUploadFolderPath = Path.Combine(Directory.GetCurrentDirectory(), configuration["mySettings:UploadsFolderPath"]);
    

    Check Permissions: Ensure the App Service has the correct permissions to delete files in the uploads folder.

    Use Absolute Path: Use Environment.GetEnvironmentVariable("HOME") to get the App Service root and construct the path.

    private readonly string myUploadFolderPath = Path.Combine(Environment.GetEnvironmentVariable("HOME"), "site", "wwwroot", configuration["mySettings:UploadsFolderPath"]);
    

    Debug the Path: Log the constructed path to verify it's correct

    Console.WriteLine("Uploads folder path: " + myUploadFolderPath);
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.