admin管理员组文章数量:1431262
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/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;
}
we have a pipeline in Azure Devops to deploy, what deployment settings to be used for write permission to be enabled.
- task: DotNetCoreCLI@2
inputs:
command: publish
publishWebProjects: true
arguments: '--configuration $(BuildConfiguration) --output $(Build.ArtifactStagingDirectory)'
#zipAfterPublish: true # commented
# this code takes all the files in $(Build.ArtifactStagingDirectory) and uploads them as an artifact of your build.
- task: AzureWebApp@1
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
inputs:
azureSubscription: 'ZOMWE(3e562eb-g31f-4241-579f-2c3e460354a1)'
appType: 'webApp'
appName: 'azvcx'
package: '$(Build.ArtifactStagingDirectory)' # added
deploymentMethod: 'auto'
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/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;
}
we have a pipeline in Azure Devops to deploy, what deployment settings to be used for write permission to be enabled.
- task: DotNetCoreCLI@2
inputs:
command: publish
publishWebProjects: true
arguments: '--configuration $(BuildConfiguration) --output $(Build.ArtifactStagingDirectory)'
#zipAfterPublish: true # commented
# this code takes all the files in $(Build.ArtifactStagingDirectory) and uploads them as an artifact of your build.
- task: AzureWebApp@1
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
inputs:
azureSubscription: 'ZOMWE(3e562eb-g31f-4241-579f-2c3e460354a1)'
appType: 'webApp'
appName: 'azvcx'
package: '$(Build.ArtifactStagingDirectory)' # added
deploymentMethod: 'auto'
Share
Improve this question
edited Nov 20, 2024 at 13:28
John
asked Nov 19, 2024 at 8:57
JohnJohn
7331 gold badge13 silver badges39 bronze badges
10
- Please share more details. – Sirra Sneha Commented Nov 19, 2024 at 9:05
- Please share the code that you've tried. – Sirra Sneha Commented Nov 19, 2024 at 9:06
- Are you sure the path is correct? – Sirra Sneha Commented Nov 19, 2024 at 9:11
- 1 what is the framework of your app (node.js,react, asp) – Sirra Sneha Commented Nov 19, 2024 at 9:16
- 1 ok will try and let you know – Sirra Sneha Commented Nov 19, 2024 at 9:28
1 Answer
Reset to default 0I created a sample Blazor application, and I can successfully upload and delete the file from the folder without any issues.
Make sure you add correct upload path in your appsettings.json
file.
appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"UploadFolderPath": "sample/uploads"
}
I used asynchronous deletion as this prevents the blocking and makes the application more responsive.
My complete 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;
}
}
}
}
Filedelete.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.";
}
}
Output after deployment:
After successfully uploading the file, we can view the file in kudu by navigating to Site -> wwwroot - > wwwroot -> sample -> uploads.
Here I've successfully deleted the files and below you can see there are no files in my kudu console.
本文标签: azureUploads folder in wwwroot doesn39t have access to delete a file by the appStack Overflow
版权声明:本文标题:azure - Uploads folder in wwwroot doesn't have access to delete a file by the app - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745571715a2664087.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论