[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How would you abort a C# Windows platform application if an array were to exceeds its boundaries "Index was outside the bounds of the array"?

Posted on 2012-08-23
2
Medium Priority
?
665 Views
Last Modified: 2012-08-24
I am developing a C# application using VS2005 on a windows platform. How would you modify the following snippet of code to end the program immediately if arr1 > 99000
and write the error "Index was outside the bounds of the array" to the file Check.err.txt

string[,] arr1 = new string[99000, 20];

-----------------------------------------------------

using System;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Collections.Generic;


namespace ReadXml1
{

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

            string goodFilePath = @"\\v\r7.1.ard.ind";
            string errorFilePath = @"\\v\Check.err.txt";

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

            DirectoryInfo parentDirectory = new DirectoryInfo(@"\\v\r");

           
            bool hasElseBeenExecuted = false;  // <-- add this boolean line to use as a check further down

            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)  // <-- change this from a regular "else" to an "else if" that specifically looks to see if the hasElseBeenExecuted variable is set to false
                    {
                        hasElseBeenExecuted = true;  // <-- set the boolean flag to true so that this else block never gets hit again
                        sw = new StreamWriter(emptyFilePath);
                        File.Copy(file.FullName, @"\\v\region\na\appl\ctrls\cashcontrol\data\prod\HarrisCheck\data\HRSBK.HARRISBK.CHKHARB4.CHKHARB4.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);                    
                }
            }


            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[99000, 20];       //where array can exceed 99,000 records
            int iCheckNumber = 0;
            String formattedString1 = null;
            String itemsequence = null;
            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";
                            itemsequence = reader.ReadElementContentAsString();
                            String formattedString = itemsequence.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("GROUP_FIELD_NAME:ItemSequence:" + itemsequence + ",GROUP_FIELD_NAME:CpcsNo" + "," + "GROUP_FIELD_VALUE:" + formattedString);
                                iCheckNumber--;
                            }
                        }
                        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);
                            formattedString1 = e.Substring(9, 6);
                            Int64 intTest = 0;

                            if (Int64.TryParse(formattedString1, out intTest))
                                arr1[i, 2] = "GROUP_FIELD_VALUE:" + formattedString1;
                            else
                            {
                                arr1[i, 2] = "GROUP_FIELD_VALUE:" + formattedString1;
                                sw1.WriteLine("GROUP_FIELD_NAME:ItemSequence:" + itemsequence + ",GROUP_FIELD_NAME:CheckNumber" + "," + "GROUP_FIELD_VALUE:" + formattedString1);
                            }

                            arr1[i, 15] = "GROUP_FIELD_NAME:OfficeNo";
                            if (Int64.TryParse(formattedString, out intTest) && intTest > 0)
                                arr1[i, 16] = "GROUP_FIELD_VALUE:" + formattedString;
                            else
                            {
                                arr1[i, 16] = "GROUP_FIELD_VALUE:" + formattedString;
                                sw1.WriteLine("GROUP_FIELD_NAME:ItemSequence:" + itemsequence + ",GROUP_FIELD_NAME:OfficeNo" + "," + "GROUP_FIELD_VALUE:" + formattedString);
                            }
                        }
                       

                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;
            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;
        }

    }
}
0
Comment
Question by:zimmer9
2 Comments
 
LVL 12

Assisted Solution

by:jmcmunn
jmcmunn earned 600 total points
ID: 38327955
Application.Exit() will exit a WinForms application.  Obviously you'd have to call your file writing routine before calling that...
0
 
LVL 23

Accepted Solution

by:
Michael Fowler earned 1400 total points
ID: 38327969
For writing to error log I like to use the following method

http://www.daveoncsharp.com/2009/09/create-a-logger-using-the-trace-listener-in-csharp/

This methods makes your life much easier. The only main difference I use is that instead creating the listener in the App.Config file I create it in the static logger class
      public static TraceListener listener;
      // Create and Initialise Trace Listener
      public static void InitialiseListener() {
         listener = new TextWriterTraceListener("Bus Status.log", "myListener");
         Trace.Listeners.Add(listener);
      }

      // Remove and Close Trace Listener. No Action on error.
      public static void CloseListener() {
         try {
            listener.Close();
            Trace.Listeners.Remove(listener);
         }
         catch (Exception) { }
      }

Open in new window


Instead of wrapping the code in a try block and using finally to close the reader you could use the "using" statement

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

As for catching the error it appears that you assign values to the array based on the value of the integer i. I cannot see where you increment i but at that point you could do something like

if (++i > 99000) {
   Logger.Error("Index was outside the bounds of the array");
   Application.Exit();
}
 
Michael
0

Featured Post

Restore individual SQL databases with ease

Veeam Explorer for Microsoft SQL Server delivers an easy-to-use, wizard-driven interface for restoring your databases from a backup. No expert SQL background required. Web interface provides a complete view of all available SQL databases to simplify the recovery of lost database

Question has a verified solution.

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

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
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…
Suggested Courses

834 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