Solved

How to avoid the error "Object reference not set to an instance of an object"?

Posted on 2011-09-02
7
341 Views
Last Modified: 2013-12-17
I am developing a C# console application. In the code that follows in the code section, do you now how I can avoid the message: "Object reference not set to an instance of an object"

It happens at the statement:  if (XmlFile(file.FullName))
when this statement is encountered for the 2nd time in the loop.
foreach (FileInfo file in parentDirectory.GetFiles())
{
   StreamWriter sw = null;
   try
   {
      if (XmlFile(file.FullName))
      {
          sw = new StreamWriter(goodFilePath);
          ProcessFile(file.FullName, sw, sw1);
      }
      else
      {
          sw = new StreamWriter(emptyFilePath);
          File.Copy(file.FullName, @"\\v\region\na\appl\ctrls\cashcontrol\data\dev\HarrisCheck\data\HRSBK.HARRISBK.THKHARB4.THKHARB4.77.1.ard.out");
      }
   }
   catch (Exception ex)
   {
       Console.WriteLine(ex.Message);
   }
   finally
   {
       if (sw != null) sw.Close();
   }
}

Open in new window

0
Comment
Question by:zimmer9
7 Comments
 
LVL 15

Expert Comment

by:dave4dl
Comment Utility
the only way you would get that error on that line was if "file" was null so add a null check to your if statement first.
0
 
LVL 13

Expert Comment

by:Naman Goel
Comment Utility
it means file object is null... This is not possible theoretically. Place one check for file object like this

replace line no 6 with  if (file != null && XmlFile(file.FullName))
0
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
When you have a problem in a loop, the problem is not necessarily in the loop code.

We do not see enough code to be able to see the problem. The file object is sent both to the XmlFile and the ProcessFile methods. What happens to file in these methods?

My hunch is that something in the ProcessFile method sets file to null.

But without seeing the code, no way to really tell.

0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

Author Comment

by:zimmer9
Comment Utility
OKay, the following is all my code in the code section:
using System;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;
using System.Globalization; 

namespace ReadXml1

{

    class Class1
    {
        static void Main(string[] args)
        {

            string goodFilePath = @"\\v\region\na\appl\ctrls\cashcontrol\data\dev\HarrisCheck\data\HRSBK.HARRISBK.THKHARB4.THKHARB4.77.1.ard.ind";
            string emptyFilePath = @"\\v\region\na\appl\ctrls\cashcontrol\data\dev\HarrisCheck\data\HRSBK.HARRISBK.THKHARB4.THKHARB4.77.1.ard";
            string tiffFilePath = @"\\v\region\na\appl\ctrls\cashcontrol\data\dev\HarrisCheck\data\HRSBK.HARRISBK.THKHARB4.THKHARB4.77.1.ard.out";
            string errorFilePath = @"\\v\region\na\appl\ctrls\cashcontrol\data\dev\HarrisCheck\data\HarrisCheck.err.txt";
            

            if (File.Exists(goodFilePath))
            {
                File.Delete(goodFilePath);
            }

            if (File.Exists(emptyFilePath))
            {
                File.Delete(emptyFilePath);
            }

            if (File.Exists(tiffFilePath))
            {
                File.Delete(tiffFilePath);
            }

            if (File.Exists(errorFilePath))
            {
                File.Delete(errorFilePath);
            }

            DirectoryInfo parentDirectory = new DirectoryInfo(@"\\v\region\na\appl\ctrls\cashcontrol\data\dev\HarrisCheck\data");
            

            StreamWriter sw1 = new StreamWriter(errorFilePath);

            bool hasElseBeenExecuted = false;  

            foreach (FileInfo file in parentDirectory.GetFiles())
            {
                StreamWriter sw = null;
                try
                {
                    if (XmlFile(file.FullName))
                    {
                        sw = new StreamWriter(goodFilePath);
                        ProcessFile(file.FullName, sw, sw1);
                    }
                    else if (!hasElseBeenExecuted)  
                    {
                        hasElseBeenExecuted = true; 
                        sw = new StreamWriter(emptyFilePath);
                        File.Copy(file.FullName, @"\\v\region\na\appl\ctrls\cashcontrol\data\dev\HarrisCheck\data\HRSBK.HARRISBK.THKHARB4.THKHARB4.77.1.ard.out");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    if (sw != null) sw.Close();
                }
            }



            if (File.Exists(errorFilePath))
            {
                if (new FileInfo(errorFilePath).Length == 0)
                {
                    if (File.Exists(errorFilePath))
                    {
                        File.Delete(errorFilePath);
                    }
                }

                else
                {
                    if (File.Exists(goodFilePath))

                        File.Delete(goodFilePath);

                    if (File.Exists(emptyFilePath))

                        File.Delete(emptyFilePath);

                    if (File.Exists(tiffFilePath))

                        File.Delete(tiffFilePath);
                }
            }
             
            
            Console.WriteLine("Processing done. Press enter to exit ... ");
            Console.ReadLine();
        }

        private static void ProcessFile(string filePath, StreamWriter sw, StreamWriter sw1)
        {
            int i = 0;
            string[,] arr1 = new string[2000, 20];
            int iCheckNumber = 0;
            XmlTextReader reader = null;
            try
            {
                reader = new XmlTextReader(filePath);
                while (reader.Read())
                {
                    
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        
                        if (reader.Name == "csc:item_sequence_number")
                        {
                            arr1[i, 11] = "GROUP_FIELD_NAME:CpcsNo";
                            String h = reader.ReadElementContentAsString();
                            String formattedString = h.Substring(7, 8);
                            Int64 intTest = 0;

                            if (Int64.TryParse(formattedString, out intTest) && intTest > 0)
                                arr1[i, 12] = "GROUP_FIELD_VALUE:" + formattedString;
                            else
                            {
                                arr1[i, 12] = "GROUP_FIELD_VALUE:" + formattedString;
                                sw1.WriteLine("COMMENT: CHECK NUMBER # " + ++iCheckNumber + ",GROUP_FIELD_NAME:CpcsNo" + "," + "GROUP_FIELD_VALUE:" + formattedString);
                                iCheckNumber--;
                            }
                        }
                    }       
                }                
                sw.WriteLine("COMMENT: specify code page of the index date");
                sw.WriteLine("CODEPAGE:819");
                for (int iter = 0; iter < i; iter++)
                {
                    for (int j = 0; j < 20; j++)
                    {
                        sw.WriteLine(arr1[iter, j]);
                    }
                }
            }
            finally
            {
                if (sw1 != null) sw1.Close();
                reader.Close();
            }
        }
        static bool XmlFile(string filePath)
        {
            string line; 
            bool xmlFile = false;
            StreamReader sr = null;
            //Regex regExpr = null;
            try
            {
                sr = new StreamReader(filePath);
                line = sr.ReadLine();
                if (line.Equals("<?xml version=\"1.0\"?>"))
                    xmlFile = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                xmlFile = false;
            }
            finally
            {
                if (sr != null) sr.Close();
            } 
            return xmlFile;
        }

    }
}

Open in new window

0
 
LVL 13

Accepted Solution

by:
Naman Goel earned 500 total points
Comment Utility
Try this

 
class Program
    {
        static void Main(string[] args)
        {
            string goodFilePath = @"\\v\region\na\appl\ctrls\cashcontrol\data\dev\HarrisCheck\data\HRSBK.HARRISBK.THKHARB4.THKHARB4.77.1.ard.ind";
            string emptyFilePath = @"\\v\region\na\appl\ctrls\cashcontrol\data\dev\HarrisCheck\data\HRSBK.HARRISBK.THKHARB4.THKHARB4.77.1.ard";
            string tiffFilePath = @"\\v\region\na\appl\ctrls\cashcontrol\data\dev\HarrisCheck\data\HRSBK.HARRISBK.THKHARB4.THKHARB4.77.1.ard.out";
            string errorFilePath = @"abcd.txt";


            if (File.Exists(goodFilePath))
            {
                File.Delete(goodFilePath);
            }

            if (File.Exists(emptyFilePath))
            {
                File.Delete(emptyFilePath);
            }

            if (File.Exists(tiffFilePath))
            {
                File.Delete(tiffFilePath);
            }

            if (File.Exists(errorFilePath))
            {
                File.Delete(errorFilePath);
            }

            DirectoryInfo parentDirectory = new DirectoryInfo(Environment.CurrentDirectory);

            

            bool hasElseBeenExecuted = false;

            foreach (FileInfo file in parentDirectory.GetFiles())
            {
                StreamWriter sw = null;
                try
                {
                    if (file!=null && XmlFile(file.FullName))
                    {
                        StreamWriter sw1 = new StreamWriter(errorFilePath);
                        sw = new StreamWriter(goodFilePath);
                        ProcessFile(file.FullName, sw, sw1);
                    }
                    else if (!hasElseBeenExecuted)
                    {
                        hasElseBeenExecuted = true;
                        sw = new StreamWriter(emptyFilePath);
                        File.Copy(file.FullName, @"\\v\region\na\appl\ctrls\cashcontrol\data\dev\HarrisCheck\data\HRSBK.HARRISBK.THKHARB4.THKHARB4.77.1.ard.out");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    if (sw != null) sw.Close();
                }
            }



            if (File.Exists(errorFilePath))
            {
                if (new FileInfo(errorFilePath).Length == 0)
                {
                    if (File.Exists(errorFilePath))
                    {
                        File.Delete(errorFilePath);
                    }
                }

                else
                {
                    if (File.Exists(goodFilePath))

                        File.Delete(goodFilePath);

                    if (File.Exists(emptyFilePath))

                        File.Delete(emptyFilePath);

                    if (File.Exists(tiffFilePath))

                        File.Delete(tiffFilePath);
                }
            }


            Console.WriteLine("Processing done. Press enter to exit ... ");
            Console.ReadLine();
        }

        private static void ProcessFile(string filePath, StreamWriter sw, StreamWriter sw1)
        {
            int i = 0;
            string[,] arr1 = new string[2000, 20];
            int iCheckNumber = 0;
            XmlTextReader reader = null;
            try
            {
                reader = new XmlTextReader(filePath);
                while (reader.Read())
                {

                    if (reader.NodeType == XmlNodeType.Element)
                    {

                        if (reader.Name == "csc:item_sequence_number")
                        {
                            arr1[i, 11] = "GROUP_FIELD_NAME:CpcsNo";
                            String h = reader.ReadElementContentAsString();
                            String formattedString = h.Substring(7, 8);
                            Int64 intTest = 0;

                            if (Int64.TryParse(formattedString, out intTest) && intTest > 0)
                                arr1[i, 12] = "GROUP_FIELD_VALUE:" + formattedString;
                            else
                            {
                                arr1[i, 12] = "GROUP_FIELD_VALUE:" + formattedString;
                                sw1.WriteLine("COMMENT: CHECK NUMBER # " + ++iCheckNumber + ",GROUP_FIELD_NAME:CpcsNo" + "," + "GROUP_FIELD_VALUE:" + formattedString);
                                iCheckNumber--;
                            }
                        }
                    }
                }
                sw.WriteLine("COMMENT: specify code page of the index date");
                sw.WriteLine("CODEPAGE:819");
                for (int iter = 0; iter < i; iter++)
                {
                    for (int j = 0; j < 20; j++)
                    {
                        sw.WriteLine(arr1[iter, j]);
                    }
                }
            }
            finally
            {
                if (sw1 != null) sw1.Close();
                
                reader.Close();
            }
        }
        static bool XmlFile(string filePath)
        {
            string line;
            bool xmlFile = false;
            StreamReader sr = null;
            //Regex regExpr = null;
            try
            {
                sr = new StreamReader(filePath);
                line = sr.ReadLine();
                if (line.Equals("<?xml version=\"1.0\"?>"))
                    xmlFile = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                xmlFile = false;
            }
            finally
            {
                if (sr != null) sr.Close();
            }
            return xmlFile;
        }

Open in new window

0
 
LVL 18

Expert Comment

by:Gary Davis
Comment Utility
I don't think file can be null after a foreach. Checking file != null before referencing it will solve the obj ref trap but may hide the real problem.

Gary Davis
Webguild
0
 
LVL 13

Expert Comment

by:Naman Goel
Comment Utility
Problem might be because we are calling Close() method for sw1(StreamWriter) object and calling constructor outside the foreach loop.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

772 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

14 Experts available now in Live!

Get 1:1 Help Now