Change in behaviour & generation of nullreference exception

Posted by peril brain on Stack Overflow See other posts from Stack Overflow or by peril brain
Published on 2010-03-10T00:29:50Z Indexed on 2010/03/31 10:03 UTC
Read the original article Hit count: 394

Filed under:

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);

    }

}

}

© Stack Overflow or respective owner

Related posts about c#