c# - 'System.AccessViolationException' occurred -


updated: added full block of code error occurs

update 2: found weird anomaly. code has been continuously breaking on line, when tabname variable equals "service line prior year". morning, grins, changed tab name "test", in turn tabname variable equals "test", , worked more not. @ loss.

i have researched ton , can't find addresses happening in code. happens randomly though. doesn't happen, other times happens in same spot, on part of code (on line templatesheet = templatebook.sheets[tabname];):

 public void exporttoexcel(dataset dataset, string filepath, int i, int h, excel.application excelapp)     {             //create excel definitions again.             //excel.application excelapp = new excel.application();             //excelapp.visible = true;             fileinfo excelfileinfo = new fileinfo(filepath);             boolean fileopentest = isfileopen(excelfileinfo);              excel.workbook templatebook;             excel.worksheet templatesheet;              //check see if template open, if not open it,             //if bind work             if (!fileopentest)             { templatebook = excelapp.workbooks.open(filepath); }             else             { templatebook = (excel.workbook)system.runtime.interopservices.marshal.bindtomoniker(filepath); }               //this grabs name of tab dump data "query dumps" tab                 string tabname = lstquerydumpsheet.items[i].tostring();                  templatesheet = templatebook.sheets[tabname];                 excelapp.calculation = excel.xlcalculation.xlcalculationmanual;                  templatesheet = templatebook.sheets[tabname];                      // copy datatable             foreach (system.data.datatable dt in dataset.tables)             {                 // copy datatable object array                 object[,] rawdata = new object[dt.rows.count + 1, dt.columns.count];                  // copy values object array                 (int col = 0; col < dt.columns.count; col++)                 {                     (int row = 0; row < dt.rows.count; row++)                     { rawdata[row, col] = dt.rows[row].itemarray[col]; }                 }                  // calculate final column letter                 string finalcolletter = string.empty;                 string colcharset = "abcdefghijklmnopqrstuvwxyz";                 int colcharsetlen = colcharset.length;                  if (dt.columns.count > colcharsetlen)                 { finalcolletter = colcharset.substring((dt.columns.count - 1) / colcharsetlen - 1, 1); }                  finalcolletter += colcharset.substring((dt.columns.count - 1) % colcharsetlen, 1);                  //this grabs cell address "query dump" sheet, splits on '=' ,                 //pulls out cell address (i.e., "address=a3" becomes "a3")                 string dumpcellstring = lstquerydumptext.items[i].tostring();                 string dumpcell = dumpcellstring.split('=').last();                  //referts range in dumping dataset.  upper right hand cell                 //defined 'dumpcell' varaible , bottom right cell defined                  //final column letter , count of rows.                 string firstref = "";                 string baserow = "";                  if (char.isletter(dumpcell, 1))                 {                     char[] createcellref = dumpcell.tochararray();                     firstref = createcellref[0].tostring() + createcellref[1].tostring();                     (int z = 2; z < createcellref.count(); z++)                     {                         baserow = baserow + createcellref[z].tostring();                     }                 }                 else                 {                     char[] createcellref = dumpcell.tochararray();                     firstref = createcellref[0].tostring();                     (int z = 1; z < createcellref.count(); z++)                     {                         baserow = baserow + createcellref[z].tostring();                     }                 }                  int baserowint = convert.toint32(baserow);                 int startingcol = columnlettertocolumnindex(firstref);                 int endingcol = columnlettertocolumnindex(finalcolletter);                  int finalcol = startingcol + endingcol;                 string endcol = columnindextocolumnletter(finalcol - 1);                 int endrow = (baserowint + (dt.rows.count - 1));                 string cellcheck = endcol + endrow;                 string excelrange;                  if (dumpcell.toupper() == cellcheck.toupper())                 {                     excelrange = string.format(dumpcell + ":" + dumpcell);                 }                 else                 {                     excelrange = string.format(dumpcell + ":{0}{1}", endcol, endrow);                 }                  //this dumps cells range on excel defined above                 templatesheet.get_range(excelrange, type.missing).value2 = rawdata;                  //checks see if sql queries have been run "query dump" tab, if not, continue                  //the loop, if last one, save workbook , move on.                  if (i == lstsqladdress.items.count - 1)                 {                     excelapp.calculation = excel.xlcalculation.xlcalculationautomatic;                      /*run through value save sheet array grab address corresponding list                      place in address array.  if address reads "whole sheet" save whole page,                     else set addresses range , value save that.*/                     //for (int y = 0; y < lstsavesheet.items.count; y++)                     //{                     //    messagebox.show("save sheet: " + lstsavesheet.items[y] + "\n" + "save address: " + lstsaverange.items[y]);                     //}                      //run macro hide unused columns                     excelapp.run("reportmakerexecute");                      //save excel file hospital name , move onto next                     savetemplateas(templatebook, h);                      //close open excel app before looping                     //marshal.releasecomobject(templatesheet);                     //marshal.releasecomobject(templatebook);                     //templatesheet = null;                     //templatebook = null;                     //gc.collect();                     //gc.waitforpendingfinalizers();                 }                 //close excel applications                 //excelapp.quit();                 //marshal.releasecomobject(templatesheet);                 //marshal.finalreleasecomobject(excelapp);                 //excelapp = null;                 //templatesheet = null;                 // gc.collect();                 //gc.waitforpendingfinalizers();             }      } 

the try/catch block of no use either. error:

"an unhandled exception of type 'system.accessviolationexception' occurred insquire (sql query retriever) v1.exe.  additional information: attempted read or write protected memory. indication other memory corrupt." 

system.accessviolationexception happen when try access unallocated memory in native code (not .net). .net translates managed world exception.

your code not have unsafe block. access violation must me happening inside excel.

given fact happens, times not, can caused parallel excel usage (i think excel com not thread-safe).

i recommend putting code inside lock block, prevent excel begin used in parallel. this:

public void exporttoexcel(dataset dataset, string filepath, int i, int h, excel.application excelapp) {     lock(this.gettype()) // can change here other instance me used mutex     {         // original code here     } } 

Comments