Solved

How to avoid the error "Object reference not set to an instance of an object" from a C# application?

Posted on 2011-03-25
1
427 Views
Last Modified: 2013-12-17
I am developing a Console application written in C# using Visual Studio 2005.
My C# code is in the following Code section.
My goal is to read 2 daily input files from a directory U:\HarrisIn. These are the only 2 files in this directory
Here is an example of the 2 daily input file names that I need to read from a directory
U:\HarrisIn
These file names are not static. Every day, the file names can change.

1) %CheckVision_lfids%MC_xml_lfids%GXSSSHDinback%POLLABLE%39fede005egc7kf4002imiro
2) %CheckVision_lfids%MC_xml_lfids%GXSSSHDinback%POLLABLE%39fede005egc72j0002imi2e

As you can see, the 2 file names to be read do not have a file extension type (such as .txt).
One of these 2 files named above ALWAYS has as its first record, the following value:
<?xml version="1.0"?>
The 2 input files have names that are not distinguishable so I cannot know from reading the file names, which of the 2 files contains has its first record the value:
<?xml version="1.0"?>

I need to read all the records from the file with this first record value, and based on the each particular record in this file, the program will execute the method ProcessFile and ultimately will generate a 1st output file named U:\Harris\HarrisCheck.ard.ind..

For the other input file, I simply want to open this file and once I determine that it doesn't contain as its first record, the value:
<?xml version="1.0"?>
I will copy this input file to a 2nd output file named U:\Harris\HarrisCheck.ard.out.
I will create a 3rd output file as an EMPTY file titled U:\Harris\HarrisCheck.ard (with no data in this file).

When the application reads each of the 2 input files, ths program does the Try statement as follows and for each input file it reads, it goes directly to the Catch statement and generates the error message
"Object reference not set to an instance of an object".

Do you know how I can resolve this error?
------------------------------------------------------
try      (in the Main Section)
                {
                    if (XmlFile(file.FullName))       (the progrma tries this statement and then goes to the Catch statement)

using System;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;
namespace ReadXml1

{

    class Class1
    {
        static void Main(string[] args)
        {
           string goodFilePath = @"U:\Harris\HarrisCheck.ard.ind";
           string badFilePath = @"U:\Harris\HarrisCheck.ard";
           DirectoryInfo parentDirectory = new DirectoryInfo(@"U:\HarrisIn");

            foreach (FileInfo file in parentDirectory.GetFiles())
            {
                StreamWriter sw = null;
                try
                {
                    if (XmlFile(file.FullName))
                    {
                        sw = new StreamWriter(goodFilePath);
                        ProcessFile(file.FullName, sw);
                    }
                    else
                    {
                        sw = new StreamWriter(badFilePath);
                        File.Copy(file.FullName, @"U:\Harris\HarrisCheck.ard.out");
                                            }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    if (sw != null) sw.Close();
                }
            }
            Console.WriteLine("Processing done. Press enter to exit ... ");
            Console.ReadLine();
        }

        private static void ProcessFile(string filePath, StreamWriter sw)
        {
            int i = 0;
            string[,] arr1 = new string[2000, 19];
            int iCheckNumber = 0;
            XmlTextReader reader = null;
            try
            {
                reader = new XmlTextReader(filePath);
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        if (reader.Name == "csc:check_number")
                        {
                            iCheckNumber = iCheckNumber + 1;
                            arr1[i, 0] = "COMMENT: CHECK NUMBER #" + iCheckNumber;
                            arr1[i, 1] = "GROUP_FIELD_NAME:CheckNumber";
                            String e = reader.ReadElementContentAsString();
                            String formattedString = e.Substring(6, 3);
                            arr1[i, 2] = "GROUP_FIELD_VALUE:" + e;
                            arr1[i, 16] = "GROUP_FIELD_VALUE:" + formattedString;
                        }
                        if (reader.Name == "csc:processing_date")
                        {
                            arr1[i, 13] = "GROUP_FIELD_NAME:CheckPaidDate";
                            String d = reader.ReadElementContentAsString();
                            String formattedDate = d.Substring(4, 2) + "/" + d.Substring(6, 2) + "/" + d.Substring(2, 2);
                            arr1[i, 14] = "GROUP_FIELD_VALUE:" + formattedDate;
                            arr1[i, 15] = "GROUP_FIELD_NAME:OfficeNo";
                        }
                        if (reader.Name == "csc:image_offset")
                        {
                            string strTemp1 = reader.ReadElementContentAsString();
                            arr1[i, 17] = "GROUP_OFFSET:" + strTemp1.PadLeft(10, '0');
                        }
                    }
                }

                for (int iter = 0; iter < i; iter++)
                {
                    for (int j = 0; j < 19; j++)
                    {
                        sw.WriteLine(arr1[iter, j]);
                    }
                }
            }
            finally
            {
                reader.Close();
            }
        }
        static bool XmlFile(string filePath)
        {
            bool xmlFile = false;
            StreamReader sr = null;
            Regex regExpr = null;
            try
            {
                regExpr = new Regex(@"<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\1>");
                MatchCollection xmlTags = regExpr.Matches(sr.ReadToEnd());
                if (xmlTags.Count > 0)
                    xmlFile = true;
                xmlTags = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                xmlFile = false;
            }
            finally
            {
                sr.Close();
            }
            return xmlFile;

        }
    }
}

Open in new window

0
Comment
Question by:zimmer9
1 Comment
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 35220492
In XmlFile(), you declare a StreamReader, but you never instantiate it. Thus, when you call ReadToEnd() you are calling it against a null object, hence the error.
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …

778 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question