Example of copying a file to another folder on a Razor page

If you want to copy files between folders on Razor pages, open each file as a FileStream and use the CopyTo method.

I created a new IActionResult called OnGetChangeFolder() that resides in my Index page code. To execute it, I call

I have a folder of cities, each one identified by its name. In this example I have a folder for Jacksonville, and another for Springfield. For each city folder, I have folders of Levels, Level1, Level2, and so on. Within each Level folder, I have a folder called Students and a folder called Teachers. I want to move the photo JohnSmith.png from the Jacksonville, Level1, Students folder to the Springfield, Level1, Students folder.

public IActionResult OnGetChangeFolder()
            var fileNamePhoto = "JohnSmith.png";
            String sourceFilePhoto = System.IO.Path.Combine(_environment.WebRootPath, "Jacksonville", "Level1", "Students") + @"\" + fileNamePhoto;
            String destFilePhoto = System.IO.Path.Combine(_environment.WebRootPath, "Springfield", "Level1", "Students") + @"\" + fileNamePhoto;
            using (FileStream src = System.IO.File.OpenRead(sourceFilePhoto))
            using (FileStream dest = System.IO.File.OpenWrite(destFilePhoto))
                src.CopyTo(dest); //blocks until finished
            return Page();

In the above code,to get the wwwroot folder where this data is stored I used _environment.WebRootPath. The _environment variable is previously defined in the IndexModel.

private Microsoft.AspNetCore.Hosting.IWebHostEnvironment _environment;
public IndexModel( Microsoft.AspNetCore.Hosting.IWebHostEnvironment environment){
_environment = environment;

I also used the System.IO.Path.Combine method to select the path of the source and destination files.

Leave a Reply

Your email address will not be published. Required fields are marked *