Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
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
?
444 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

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…
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
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…

618 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