An exception of type 'System.OutOfMemoryException' occurred in mscorlib.dll but was not handled in user code asp.net

2

I'm having trouble getting this error resolved. My purpose is to collect data from an Excel file storing it in C # variables, which in turn will be inserted in SQL Server 2012. Reading is done line by line. Here is the code where the error happens:

Excel.Application excelApp = new Excel.Application();
Excel.Workbook WB = null;
Excel.Worksheet WS = null;
excelApp.Visible = false;


Convert.ToString(FileUpload1.PostedFile.FileName);
Response.Write(FileUpload1.PostedFile.FileName);



string excelpath = FileUpload1.PostedFile.FileName;
Convert.ToString(excelpath);

string workbookPath = excelpath;

WB = excelApp.Workbooks.Open(workbookPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
WS = excelApp.Worksheets.get_Item("" + TextBox2.Text); 


String connectionString =
   "Data Source=localhost;" +
   "Initial Catalog=Teste;" +
   "User id=sa;" +
   "Password=123;";

Excel.Range last = WS.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell);
Excel.Range range = WS.get_Range("A1", last);
object ranger = range.Value;

Error:

  

An exception of type 'System.OutOfMemoryException' occurred in mscorlib.dll but was not handled in user code asp.net

    
asked by anonymous 24.02.2017 / 10:50

1 answer

0

OutOfMemoryException has no way to recover in the traditional way, it is thrown when your application runs out of memory, this is due to the fact of reading 400 * 142 whole strings into memory, you could divide, read the first line and issue the data, then read the second and send the data, do not read everything at once if it will not be without memory itself. this ranger is getting the value of the WHOLE worksheet, try to make two of them each for a section of the worksheet, or maybe three.

    
26.02.2017 / 14:35