0

I have built an ASP.NET Core web app which allows users to upload an Excel file for processing. It has been published but some users are now sporadically experiencing file upload errors. It has worked for these same users previously and I am unable to replicate it so it is causing confusion.

Here is the relevant code: //controller method:

    [HttpPost]
    public ActionResult UploadToServer()
    {
        

        //get session ID and Windows domain name
        var sessId = HttpContext.Session.GetString("CurrentLoad");
        var userName = _httpContextAccessor.HttpContext.User.Identity.Name;

        Log.Info($"File selected for upload to server by user {userName}.");
        Log.Info($"Session ID for this load is {sessId}");
        
        var files = Request.Form.Files;

        if (files.Count > 0)
        {
            try
            {
                var fileUploader = new FileUploader(_config, files, _dbContext);
                fileUploader.UploadFile(sessId, userName);
                Log.Info("File uploaded to server");
            }
            catch (Exception e)
            {
                Log.Error("File upload has failed: " + e);
                throw;
            }

        }

        else
        {
            Log.Error("No files selected for upload.");
        }

        return new EmptyResult();
    }

//my FileUploader helper:

public class FileUploader
{
    private readonly IConfiguration _config;
    private readonly DatabaseContext _dbContext;
    private readonly IEnumerable<IFormFile> _uploads;
    private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
    private LoadHelper _loadHelper;


    public FileUploader(IConfiguration config, IEnumerable<IFormFile> uploads, DatabaseContext dbContext)
    {
        _config = config;
        _uploads = uploads;
        _dbContext = dbContext;
    }

    public void UploadFile(string sessionId, string userName)
    {

        Log.Info("File selected for upload to server");
        var uploadsPath = Directory.GetCurrentDirectory() + _config["uploadFolder"];
        var inputPath = Directory.GetCurrentDirectory() + _config["inputFolder"];

        foreach (var file in _uploads)
        {
            try
            {
                if (!Directory.Exists(uploadsPath))
                    Directory.CreateDirectory(uploadsPath);

                using (var fileStream = File.Create(Path.Combine(uploadsPath, file.FileName)))
                {
                    file.CopyTo(fileStream);
                    fileStream.Flush();
                }

                Log.Info($"File {file.FileName} successfully uploaded to web server");

                MoveFile(uploadsPath, file);
                Log.Info($"File {file.FileName} moved across to Input folder to start");

                var fullPath = Path.Combine(inputPath, file.FileName);
                Log.Info($"Full path of upload file is {fullPath}. Ready to process");

                //this section initialises the LoadFileModel from the uploaded file, then writes everything to DB for processing
                var loadFile = new LoadFileModel();

                _loadHelper = new LoadHelper(loadFile);
                loadFile = _loadHelper.InitialiseLoadFileModel(fullPath, file, userName);
                DatabaseWrite(loadFile, sessionId);

            }
            catch (Exception e)
            {
                Log.Error($"File upload from UI has failed: " + e);
                throw;
            }
        }

    }
}

//Below is the error from the log files after the user tries and fails to upload a file:

2020-09-16 14:18:35,692 [69] ERROR Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware [? ?] - An unhandled exception has occurred while executing the request. System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\username\Desktop\Data Request.xlsx'. at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle) at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at LGL.FrontEnd.Helpers.FileUploader.UploadFile(String sessionId, String userName)

Barrassment
  • 75
  • 1
  • 7
  • Directory.GetCurrentDirectory() is not something you want to use, you can't assume it has a specific value, use one of these methods: https://stackoverflow.com/questions/43709657/how-to-get-root-directory-of-project-in-asp-net-core-directory-getcurrentdirect to get the app's root and base your paths on that. – Alex K. Sep 16 '20 at 14:26
  • As the error message said "could not find the file from the path", try to set debugger in the UploadFile method and check the path, and check whether the excel file is exist or not? And, as Alex said, you could try to use [IWebHostEnvironment](https://www.aspsnippets.com/Articles/Using-IWebHostEnvironment-in-ASPNet-Core.aspx) to get the content path or root path. Besides, it seems that in the UploadFile method, you also call the MoveFile method to remove the file, try to set break point to find which line will show this error, it might be easier to find the solution. – Zhi Lv Sep 17 '20 at 06:35

0 Answers0