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
421 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 74

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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

705 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now