MRP
MRP

Reputation: 609

How to use IFileInfo to delete a file in ASP.NET Core

I have read that it's better I use IFileProvider for managing files in ASP.NET Core Microsoft Documentation. but, if I use GetFileInfo() method I will have access to IFileInfo and it just provides some methods for reading files!

How can I delete a file?

Upvotes: 2

Views: 8439

Answers (1)

Rob
Rob

Reputation: 45780

You've suggested in comments that your concern is the different form of paths in different Operating Systems that your code may be running on. As long as you don't try to string.Concat or + bits of your paths together, build them up in a StringBuilder or in any other way try to pretend that you'll be able to build a valid path yourself in any circumstances you'll be fine :). The filesystem related classes in the System.IO namespace are there specifically to help you to get this right, so do use them.

If you've already got an instance of IFileProvider from somewhere else (say that's what you're using the enumerate the files to display to users so they can choose which ones to delete), you can mix-and-match that with System.IO, perhaps with something like this:

public void SomeMethodThatsCalled()
{
    // I'm presuming there's a lot of other code here, and that the IFileProvider
    // is actually dependency injected somewhere, somehow, but it's self-contained
    // here for completeness
    IFileProvider physicalFileProvider = new PhysicalFileProvider(@"D:\DeleteMyContentsPlease\");

    DeleteFiles(physicalFileProvider);
}

private void DeleteFiles(IFileProvider physicalFileProvider)
{
    if (physicalFileProvider is PhysicalFileProvider)
    {
        var directory = physicalFileProvider.GetDirectoryContents(string.Empty);
        foreach (var file in directory)
        {
            if (!file.IsDirectory)
            {
                var fileInfo = new System.IO.FileInfo(file.PhysicalPath);
                fileInfo.Delete();

            }
        }
    }
}

There's absolutely no error-checking, validation, exception handling or anything else that would remotely make this production code present here (with the possible exception of actually checking that the entry in the directory isn't a directory!) so please don't use it as-is.

Equally: If you've not got an instance of IFileSystem from anywhere, don't feel particularly obliged to create one just to delete files!

Upvotes: 7

Related Questions