Solved

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

Posted on 2011-09-02
7
360 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
Technology Partners: 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

Enroll in May's Course of the Month

May’s Course of the Month is now available! Experts Exchange’s Premium Members and Team Accounts have access to a complimentary course each month as part of their membership—an extra way to increase training and boost professional development.

Question has a verified solution.

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

Suggested Solutions

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

710 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