Issue
I'm using Windows OS and Visual Studio to develop web apps. I use Ubuntu Server 22.04 (LTS) as production OS. I can run my app on Ubuntu 22.04 and it works fine but the part of app which clients can upload their files does not work and causes error 500. Unfortunately, I develop my app on Windows and I cannot debug it. After lots of trials, I found the section causes error 500. The following is the section of code that I use for uploading file:
[HttpPost]
[Authorize]
public async Task<IActionResult> UploadNewPmFile(IList<IFormFile> uploadedFile)
{
.
.
.
var fileName = Path.GetFileName(file.FileName);
var fileExtension = Path.GetExtension(fileName);
var newFileName = string.Concat(userId, fileExtension);
var path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Data\Temp", newFileName);
using (var stream = new FileStream(path, FileMode.Create)) //***Error is here***
{
await file.CopyToAsync(stream);
}
.
.
.
}
As you see, using
section causes error 500 on Ubuntu but it works fine on WIndows.
I'm using .NET 8.0 runtime on both Windows and Ubuntu.
I searched many questions on this site but I could not find anything related to sole this.
How can I fix this problem?
Update: Note that the published app works fine and without error on Windows but the file uploading section does not work on Ubuntu.
Solution
Linux/Unix use /
as the directory path character whereas Windows uses \
. See Path.DirectorySeparatorChar for more information.
The code in the OP contains:
var path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Data\Temp", newFileName);
One can remove \
and rewrite the code as:
Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Data", "Temp", newFileName);
This will allow Path.Combine to use the correct directory separator character for the operating system that the code is running on.
For information on remote debugging, see Debug .NET Core on Linux using SSH by attaching to a process.
Answered By - user246821 Answer Checked By - Willingham (WPSolving Volunteer)