richard smith

richard smith

  • 1.5k
  • 285
  • 160.2k

C# to only run a block of code once

Mar 13 2013 3:45 PM
You guys may be able to tell me a better way to do this, but what I am wanting to do is I have a statement in my C# that creates a new instance of excel then codes...for example:
_Application docExcel = new Microsoft.Office.Interop.Excel.Application();
docExcel.Visible = true;
docExcel.DisplayAlerts = false;
_Workbook workbooksExcel = docExcel.ActiveWorkbook;
workbooksExcel = (_Workbook)(docExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet));
Worksheet worksheet = (Worksheet)docExcel.Worksheets["Sheet1"];

//more code down here to export datagrid to Excel

So with that being said, each time my function is called, I do not want it to run the above code, I only want it to run the above code if EXCEL IS NOT OPEN, OR this is the 1st time function is run.  How can I do this in C#?

Answers (9)