Home » excel » c# – Save file uploaded on azurewebsite

c# – Save file uploaded on azurewebsite

Posted by: admin April 23, 2020 Leave a comment

Questions:

On my local machine everything works well but..

After publishing my MVC4 web project there is a problem with an uploaded Excel file.
I load an HttpPostedFileBase and send the path to my BL. There I load it to dataTable and on my second call I get it to a list.

Here is the code..

Controller:

  [HttpPost]
    public ActionResult UploadCards(HttpPostedFileBase file, string sheetName, int ProductID)
    {
        try
        {
            if (file == null || file.ContentLength == 0)
                throw new Exception("The user not selected a file..");

            var fileName = Path.GetFileName(file.FileName);
            var path = Server.MapPath("/bin");

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            path = Path.Combine(path, fileName);
            file.SaveAs(path);

            DataTable cardsDataTable = logic.LoadXLS(path, sheetName);
            cardsToUpdate = logic.getUpdateCards(cardsDataTable, ProductID);

            foreach (var item in cardsToUpdate)
            {
                if (db.Cards.ToList().Exists(x => x.SerialNumber == item.SerialNumber))
                    cardsToUpdate.Remove(item);
            }
            Session["InfoMsg"] = "click update to finish";
        }
        catch (Exception ex)
        {
            Session["ErrorMsg"] = ex.Message;
        }
        return View("viewUploadCards", cardsToUpdate);
    }

BL:

     public DataTable LoadXLS(string strFile, String sheetName)
    {
        DataTable dtXLS = new DataTable(sheetName);

        try
        {
            string strConnectionString = "";

            if (strFile.Trim().EndsWith(".xlsx"))
                strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
            else if (strFile.Trim().EndsWith(".xls"))
                strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);

            OleDbConnection SQLConn = new OleDbConnection(strConnectionString);

            SQLConn.Open();

            OleDbDataAdapter SQLAdapter = new OleDbDataAdapter();

            string sql = "SELECT * FROM [" + sheetName + "$]";

            OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn);

            SQLAdapter.SelectCommand = selectCMD;

            SQLAdapter.Fill(dtXLS);

            SQLConn.Close();

        }

        catch (Exception ex)
        {
            string res = ex.Message;
            return null;
        }

        return dtXLS;
    }

and:

    public List<Card> getUpdateCards(DataTable dt, int prodId)
    {
        List<Card> cards = new List<Card>();
        try
        {
            Product product = db.Products.Single(p => p.ProductID == prodId);
            foreach (DataRow row in dt.Rows)
            {
                cards.Add(new Card
                {
                    SerialNumber = row[0].ToString(),
                    UserName = row[1].ToString(),
                    Password = row[2].ToString(),

                    Activated = false,

                    Month = product.Months,
                    Bandwidth = product.Bandwidth,
                    ProductID = product.ProductID,
                    // Product = product
                });
            }
        }
        catch (Exception ex)
        {
            db.Log.Add(new Log { LogDate = DateTime.Now, LogMsg = "Error : " + ex.Message });

        }
        return cards;
    }

Now I think Windows Azure doesn’t let me save this file because on the middle view when I supposed to see the data – I don’t see it.

I thought of some ways…
one – not saving the file, but I don’t see how to complete the ConnectionString
second maybe there is a way to save the file there.

I’d love to get suggestions for solving this problem…

10x and sorry for my bad English =)

How to&Answers:

I’m embarrassed but I found a similar question here.. Not exactly but it gave me a good direction.

Hare the finally result:

[HttpPost]
    public ActionResult UploadCards(HttpPostedFileBase file, string sheetName, int ProductID)
    {
        IExcelDataReader excelReader = null;
        try
        {
            if (file == null || file.ContentLength == 0)
                throw new Exception("The user not selected a file..");

            if (file.FileName.Trim().EndsWith(".xlsx"))
                excelReader = ExcelReaderFactory.CreateOpenXmlReader(file.InputStream);
            else if (file.FileName.Trim().EndsWith(".xls"))
                excelReader = ExcelReaderFactory.CreateBinaryReader(file.InputStream);
            else
                throw new Exception("Not a excel file");

            cardsToUpdate = logic.getUpdateCards(excelReader.AsDataSet().Tables[sheetName], ProductID);

            foreach (var item in cardsToUpdate)
            {
                if (db.Cards.ToList().Exists(x => x.SerialNumber == item.SerialNumber))
                    cardsToUpdate.Remove(item);
            }
            Session["InfoMsg"] = "Click Update to finish";
        }
        catch (Exception ex)
        {
            Session["ErrorMsg"] = ex.Message;
        }
        finally
        {
            excelReader.Close();
        }
        return View("viewUploadCards", cardsToUpdate);
    }  

10q all.

EDIT: download, reference and using

the dll is avalibale hare
i add the reference to the Excel.dll and i add the using Excel;

Answer:

The problem might be caused by writing the file to the disk. Cloud providers usually do not allow the applications to write to the disk.

In your case it seems that the file is written to the disk only temporary and is loaded directly to the DB. You should be able to open the stream from the uploaded file directly and write it directly to the DB – without writing to the disk.

Check the exception which you are stocking in the Session – you should find more information there.

Answer:

@hoonzis is right, writing files to disk in the cloud is not permited(you can’t event get or set a path for the file). You should use blob storage, much more efficient for files and is cheaper than sql. I recommend to use the table storage service, it is noSQL but it’s more cheaper than azure sql.
Use azure sql only if it is a must for your solution.

Blob storage see more details here: http://www.windowsazure.com/en-us/develop/net/how-to-guides/blob-storage/

Table storage: http://www.windowsazure.com/en-us/develop/net/how-to-guides/table-services/

Some more information about choosing the right storage you can find here: http://www.windowsazure.com/en-us/develop/net/fundamentals/cloud-storage-scenarios/