Click here to Skip to main content
15,883,919 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more: , +
I work on asp.net core 2.2 web API using C# language

I need to rewrite function below with best syntax and with best practice

web API below get Excel file from upload and return Excel file

it working without any issue but I need to rewrite it with best syntax and practice

some points I need to changes :

concatenate path is best thing using

are streaming using correctly

are memory copying file is correct

What I have tried:

ASP.NET
[HttpPost, DisableRequestSizeLimit]
    [Route("Upload")]
    public IActionResult Upload()
    {
        try
        {
            var DisplayFileName = Request.Form.Files[0];
            string fileName = DisplayFileName.FileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";
            string Month = DateTime.Now.Month.ToString();
            string DirectoryCreate = myValue1 + "\\" + Month + "\\" + fileName;
            string exportDirectory = myValue2 + "\\" + Month;
            string exportPath = myValue2 + "\\" + Month + "\\" + fileName;
            string FinalPath = exportPath;
           
            if (!Directory.Exists(DirectoryCreate))
            {
                Directory.CreateDirectory(DirectoryCreate);
       
            }
            if (!Directory.Exists(exportDirectory))
            {
                Directory.CreateDirectory(exportDirectory);
      
            }
            CExcel ex = new CExcel();
            if (DisplayFileName.Length > 0)
            {
                var filedata = ContentDispositionHeaderValue.Parse(Request.Form.Files[0].ContentDisposition).FileName.Trim('"');
                var dbPath = Path.Combine(DirectoryCreate, fileName);
            
                using (var stream = new FileStream(dbPath, FileMode.Create))
                {
                    Request.Form.Files[0].CopyTo(stream);
                    stream.Flush();
                    stream.Close();
                }
                GC.Collect();
                string error = "";
                int rowCount = 0;
                string inputTemplatePath = "";
              
                var InputfilePath = System.IO.Path.Combine(GetFilesDownload, "DeliveryGeneration_Input.xlsx");
                bool areIdentical = ex.CompareExcel(dbPath, InputfilePath, out rowCount, out error);
                if (areIdentical == true)
                {
                    List<InputExcel> inputexcellist = new List<InputExcel>();
                    inputexcellist = ex.Import(dbPath);
                    List<string> mods = new List<string>();
                    mods = inputexcellist.Select(x => x.ModuleName).Distinct().ToList();
                    var OutputfilePath = System.IO.Path.Combine(GetFilesDownload, "DeliveryGeneration_Output.xlsx");
                    if (System.IO.Directory.Exists(Path.Combine(exportDirectory, fileName)))
                    {
                        throw new Exception("Ok so the error message IS right.");
                    }
                    System.IO.File.Copy(OutputfilePath, Path.Combine(exportDirectory, fileName), true);
    
                    SqlConnection con;
                    foreach (var m in mods)
                    {
                        List<InputExcel> inputmodulelist = new List<InputExcel>();
                        inputmodulelist = inputexcellist.Where(x => x.ModuleName == m).ToList();
                        var dtimport = DatatableConversion.ToDataTable(inputmodulelist);
                        DataTable dtexport = new DataTable();
                        dtexport = _deliveryService.LoadExcelToDataTable(_connectionString, dtimport);
                        ex.Export(dtexport, m, exportPath);
    
                    }
                }
                var memory2 = new MemoryStream();
                using (var stream = new FileStream(exportPath, FileMode.Open))
                {
                    stream.CopyTo(memory2);
                }
                memory2.Position = 0;
    
                return File(memory2, "text/plain", Path.GetFileName(exportPath));
    
            }
            else
            {
                return BadRequest();
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Internal server error: {ex}");
        }
    }
Posted
Updated 31-Aug-21 0:26am

1 solution

Where to start?
Quote:
C#
string fileName = DisplayFileName.FileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";
Should be:
C#
string fileName = Path.GetFileNameWithoutExtension(DisplayFileName.FileName) + "-" + Guid.NewGuid().ToString() + Path.GetExtension(DisplayFileName.FileName);

Quote:
C#
string DirectoryCreate = myValue1 + "\\" + Month + "\\" + fileName;
string exportDirectory = myValue2 + "\\" + Month;
string exportPath = myValue2 + "\\" + Month + "\\" + fileName;
You should probably be using Path.Combine here - eg:
C#
string DirectoryCreate = Path.Combine(myValue1, Month, fileName);
Also myValue1 and myValue2 are not defined anywhere.

Quote:
C#
var filedata = ContentDispositionHeaderValue.Parse(Request.Form.Files[0].ContentDisposition).FileName.Trim('"');
You already have the file name - DisplayFileName.FileName. You don't need to parse the ContentDisposition header to extract it again.

Quote:
C#
GC.Collect();
That is almost always the wrong thing to do - especially in a multi-user environment like ASP.NET.

Quote:
C#
throw new Exception("Ok so the error message IS right.");
You should be throwing a more specific exception type, and providing a meaningful message here.

Quote:
C#
SqlConnection con;
Why have you declared this variable when you never use it?

I'm sure there would be plenty of other problems if we knew what the code was supposed to be doing.
 
Share this answer
 
Comments
ahmed_sa 31-Aug-21 17:47pm    
thank you very much
1- first question are using memory stream like below is correct
var memory2 = new MemoryStream();
using (var stream = new FileStream(exportPath, FileMode.Open))
{
stream.CopyTo(memory2);
}
memory2.Position = 0;
2-second question when I have exception file using by another process
so How to solve issue
3- Are using async task wait will have benefit or no need

can you please answer me on this comment
please hel me
Richard Deeming 1-Sep-21 3:50am    
There's no point reading the file into a MemoryStream just to send it to the client. You can replace that block with:
return PhysicalFile(exportPath, "text/plain", Path.GetFileName(exportPath));


If you're getting an error saying the file is in use, then either another process has opened the file, or your code is not closing the file. Debug your code to find out where the exception is thrown, and check which process has the file open.

Async tasks will be beneficial if you are waiting on IO-bound code - for example, accessing a database or the file system.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900