wwwroot 中的Uploads 文件夹无权通过应用程序删除文件

问题描述 投票:0回答:1

我的应用服务中有一个

Uploads
文件夹,并且上传成功。

但是,当应用程序尝试删除上传的文件时,遇到错误:

System.IO.IOException:对内存位置的访问无效。 : 'C:\home\site\wwwroot\wwwroot\sample\uploads\MyFile.txt'

我看到的结构是:

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;
}
azure blazor azure-appservice
1个回答
0
投票

我创建了一个示例 Blazor 应用程序,我可以成功上传和从文件夹中删除文件,没有任何问题。

确保在

appsettings.json
文件中添加正确的上传路径。

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "UploadFolderPath": "sample/uploads" 
}

我使用异步删除,因为这可以防止阻塞并使应用程序响应更快。

我的完整FileService.cs

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace FileUploadApp.Services
{
    public class FileService
    {
        private readonly string _uploadFolderPath;
        private readonly ILogger<FileService> _logger;

        public FileService(IConfiguration configuration, ILogger<FileService> logger)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger)); 
        
            var uploadFolderPathConfig = configuration["UploadFolderPath"];

            if (string.IsNullOrEmpty(uploadFolderPathConfig))
            {
                throw new ArgumentNullException(nameof(uploadFolderPathConfig), "Upload folder path cannot be null or empty.");
            }

            _uploadFolderPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", uploadFolderPathConfig);

            _logger.LogInformation($"Upload folder path: {_uploadFolderPath}");

            if (!Directory.Exists(_uploadFolderPath))
            {
                Directory.CreateDirectory(_uploadFolderPath);
                _logger.LogInformation("Created upload folder.");
            }
        }

        public async Task<bool> UploadFile(Stream fileStream, string fileName)
        {
            try
            {
                if (string.IsNullOrEmpty(_uploadFolderPath))
                {
                    _logger.LogError("Upload folder path is null or empty.");
                    return false;
                }

                var filePath = Path.Combine(_uploadFolderPath, fileName);
                _logger.LogInformation($"Uploading file to {filePath}");

                using (var file = new FileStream(filePath, FileMode.Create))
                {
                    await fileStream.CopyToAsync(file);
                }

                _logger.LogInformation("File uploaded successfully.");
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError($"Error uploading file: {ex.Message}");
                return false;
            }
        }

        public async Task<bool> RemoveUploadedFiles()
        {
            try
            {
 
                if (Directory.Exists(_uploadFolderPath))
                {
                    var files = Directory.GetFiles(_uploadFolderPath);
                    foreach (var file in files)
                    {
                        await Task.Run(() => File.Delete(file));  
                    }
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError($"Error deleting files: {ex.Message}");
                return false;
            }
        }
    }
}

文件删除.razor:

@page "/file-delete"
@using FileUploadApp.Services
@inject FileService FileService

<h3>Delete Uploaded Files</h3>

<button @onclick="DeleteFiles">Delete All Files</button>
<p>@statusMessage</p>

@code {
    private string statusMessage;

    private async Task DeleteFiles()
    {
        var success = await FileService.RemoveUploadedFiles();

        statusMessage = success ? "All files deleted successfully!" : "Failed to delete files.";
    }
}

部署后输出:

enter image description here

成功上传文件后,我们可以通过导航到 Site -> wwwroot -> wwwroot -> Sample -> uploads 在 kudu 中查看该文件。

enter image description here

enter image description here

这里我已经成功删除了文件,下面你可以看到我的 kudu 控制台中没有文件。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.