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
432 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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

820 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