Change in behaviour & generation of nullreference exception
- by peril brain
I made this program 2hr ago and it ran quit well when i confronted this to presaved .xls file. But when i closed that and started new instance,it started generating null refrence exception why??plz explain.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using Microsoft.Office.Interop;
using Excel = Microsoft.Office.Interop.Excel;
namespace svchost
{
class MainClass
{
Excel.Application oExcelApp;
static void Main(string[] args)
{
MainClass mc = new MainClass();
while (true)
{
if (mc.chec())
{
Console.WriteLine("RUNNING");
Thread.Sleep(4000);
}
else
{
Console.WriteLine("NOT RUNNING");
Thread.Sleep(8000);
}
}
}
public bool chec()
{
try
{
oExcelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
Excel.Workbook xlwkbook = (Excel.Workbook)oExcelApp.ActiveWorkbook;
//****PROBLEM FROM HERE*********
Console.WriteLine(xlwkbook.Name + "\n");
ke kw = new ke(ref oExcelApp,ref xlwkbook);
Console.WriteLine(xlwkbook.Author);
xlwkbook = null;
}
catch (Exception ec)
{
oExcelApp = null;
System.GC.Collect();
Console.WriteLine(ec);
return false;
}
oExcelApp = null;
System.GC.Collect();
return true;
}
}
class ke
{
public ke(ref Excel.Application a1, ref Excel.Workbook b1)
{
Excel.Worksheet ws = (Excel.Worksheet)a1.ActiveSheet;
Console.WriteLine(a1.ActiveWorkbook.Name + "\n" + ws.Name);
Excel.Range rn;
rn = ws.Cells.Find("657/07", Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing);
Console.WriteLine(rn.Text);
}
}
}