IFileInfo.PhysicalPath is empty
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 6h
- Merged PRs (30d)
- 290
Description
### Is there an existing issue for this?
- [X] I have searched the existing issues
### Describe the bug
I have a web application where I can upload files. The files are associated with data in a database. In the database I only store the relative file path to the uploaded file. The file as such should be stored in a special folder in my wwwroot like `wwwroot/uploads/<>/` where <> will be the Id of the entity in the database.
With the following code I try to create the file:
```csharp
private IWebHostEnvironment _env; // will be set in the constructor
private void StoreFile(string path, string content)
{
var fi = new FileInfo(_env.WebRootFileProvider.GetFileInfo(path).PhysicalPath);
if (!fi.Directory.Exists)
fi.Directory.Create();
using (var writer = fi.CreateText())
{
writer.Write(vm.Content);
}
}
```
So when I try to run this code, I discovered, that the `PhysicalPath` of the `IFileInfo` is null because the file doesn't exist.

But I already did something like that in an earlier project (.Net < 6.0) and with that it worked fine. The `PhysicalPath` wasn't null, even when the file doesn't exists.
After some debugging I found out, that the `WebRootFileProvider` of the `IWebHostEnvironment` is a `Microsoft.Extensions.FileProviders.CompositeFileProvider` which contains two extra file providers:
1. Microsoft.AspNetCore.StaticWebAssets.ManifestStaticWebAssetFileProvider and
2. Microsoft.Extensions.FileProviders.PhysicalFileProvider

In the debug console of VSCode I did some test and I found that if I call the PhysicalFileProvider directly, the IFileInfo conains the physical path even if the file doesn't exists:

The implementation of the `IFileInfo` is of type `PhysicalFileInfo`
But when I use the `ManifestStaticWebAssetFileProvider` I get the the result with the null value:

The implementation of the `IFileInfo` is now of type `NotFoundFileInfo`.
### Expected Behavior
The physical path should be set nonetheless if the file exists or not.
### Steps To Reproduce
Try to create a new file with the code above.
### Exceptions (if any)
_No response_
### .NET Version
6.0.125
### Anything else?
```
.NET SDK (reflecting any global.json):
Version: 6.0.125
Commit: e898a826c2
Runtime Environment:
OS Name: ubuntu
OS Version: 22.04
OS Platform: Linux
RID: ubuntu.22.04-x64
Base Path: /usr/lib/dotnet/sdk/6.0.125/
global.json file:
Not found
Host:
Version: 6.0.25
Architecture: x64
Commit: 492abbeef0
.NET SDKs installed:
6.0.125 [/usr/lib/dotnet/sdk]
.NET runtimes installed:
Microsoft.AspNetCore.App 6.0.25 [/usr/lib/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 6.0.25 [/usr/lib/dotnet/shared/Microsoft.NETCore.App]
```
The application runs in a Codespace-Container.
Contributor guide
Assessment
This issue has not been assessed yet.