Solved

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

Posted on 2011-09-02
7
363 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
[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
7 Comments
 
LVL 15

Expert Comment

by:dave4dl
ID: 36476818
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
ID: 36476825
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
ID: 36476830
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
Independent Software Vendors: 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!

 

Author Comment

by:zimmer9
ID: 36477022
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
ID: 36477209
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
ID: 36477750
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
ID: 36478384
Problem might be because we are calling Close() method for sw1(StreamWriter) object and calling constructor outside the foreach loop.
0

Featured Post

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

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…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

617 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