?
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
Medium Priority
?
441 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 2000 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
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:…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses

801 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