Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2011-09-02
7
Medium Priority
?
376 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
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

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 2000 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

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…
High user turnover can cause old/redundant user data to consume valuable space. UserResourceCleanup was developed to address this by automatically deleting user folders when the user account is deleted.
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…

877 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