Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

C# Array ignoring last entry in the array

Posted on 2010-09-09
8
Medium Priority
?
318 Views
Last Modified: 2012-05-10
I have this piece of code that reads a text file, looks for certain values in each line, then increments some integer variables for success or failures. Right now it currently ignores the first line in the file, and now I need it to ignore the last line in the file also. I'm sure it's a simple fix, but the answer has been eluding me. I read the whole file into a variable, then split the file into separate lines. Then I split each line on the commas, to allow the code to search for the specified string.


>Exchange Zone removed by a3
public string ReadFileBoardResp(string fileName)
        {
            try
            {

                StreamReader sr = new StreamReader(fileName);
                boardLine = sr.ReadToEnd();
                string Contents = boardLine;
                string[] lines = Contents.Split(char.Parse("\r"));
                int x = 0;
                successCount = 0;
                failureCount = 0;
                while (lines[x].ToString() != "\n")
                {
                    string[] parts = lines[x].Split(char.Parse(","));
                    x++;
                    boardRespID = Contents.Substring(11, 7);
                    if (x != 1)
                    {
                        if (parts[4].ToString() == "\"SUCCESSFUL in MAP\"")
                        {
                            successCount++;
                        }
                        else
                        {
                            failureCount++;
                        }
                    }
                }
                sr.Close();
                 
            }
            catch (Exception e)
            {
                Add.AddToFile(e.Message.ToString());

            } 
            return boardLine; 
        }

Open in new window

0
Comment
Question by:Abacus IT
[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
8 Comments
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 33636050
question: why do you have this condition:if (x != 1)should that not be the explanation?
0
 
LVL 1

Author Comment

by:Abacus IT
ID: 33636117
That condition is ignoring the first line in the file. My assumption is that ignoring the last line would be something very similar.
0
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 252 total points
ID: 33636162
ok, why don't you do like this:
public string ReadFileBoardResp(string fileName)
        {
            try
            {

                StreamReader sr = new StreamReader(fileName);
                boardLine = sr.ReadToEnd();
                string Contents = boardLine;
                string[] lines = Contents.Split(char.Parse("\r"));
                int x = 1;
                successCount = 0;
                failureCount = 0;
                while (x < lines.Length && lines[x].ToString() != "\n")
                {
                    string[] parts = lines[x].Split(char.Parse(","));
                    x++;
                    boardRespID = Contents.Substring(11, 7);

                        if (parts[4].ToString() == "\"SUCCESSFUL in MAP\"")
                        {
                            successCount++;
                        }
                        else
                        {
                            failureCount++;
                        }
                }
                sr.Close();
                 
            }
            catch (Exception e)
            {
                Add.AddToFile(e.Message.ToString());

            } 
            return boardLine; 
        }

Open in new window

0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 52

Assisted Solution

by:Carl Tawn
Carl Tawn earned 248 total points
ID: 33636165
Try changing your condition to the following:

    if (x != 1 && x < lines.Count-1)
0
 
LVL 1

Author Comment

by:Abacus IT
ID: 33636373
@Carl, the issue is that I need it to be in a while loop so that it iterates through the lines.
@angel, I tried the code change you supplied, but it still doesn't ignore the last line of the file.

So, what I did was combine what you both supplied and went with:

while (x < lines.Length - 1 && lines[x].Tostring() != "\n")

Unfortunately that still seems to include the last line in the file to the failurecount variable.
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 33636412
>but it still doesn't ignore the last line of the file.

if the last list has \n only, you want to actually skip the last 2 items from the array?
OR, if you have the file splitted by \r\n  and not \r, you could remove that test on \n ?
0
 
LVL 1

Author Comment

by:Abacus IT
ID: 33636477
Yea, I guess that's what I would want then, to skip the last 2 items from the array.

I changed  the condition to read:

while (x < lines.Length - 2 && lines[x].Tostring() != "\n")

And this got me the exact result I wanted.
0
 
LVL 7

Expert Comment

by:jdavistx
ID: 33636613
You also don't need to use .ToString() on string array elements, and you should encapsulate your StreamReader with a using statement. From your excerpt, your boardLine variable is also not needed.  Of course, maybe you're using these variable else where, but it would appear your code could, in part, be shorted a few lines.




public string ReadFileBoardResp(string fileName)
{
	try
	{
		using(StreamReader sr = new StreamReader(fileName))
		{
			string[] lines = sr.ReadToEnd().Split(char.Parse("\r"));
			int x = 0;
			successCount = 0;
			failureCount = 0;

			while (x != 0 && x != lines.Length-1 && lines[x] != "\n")
			{
				string[] parts = lines[x].Split(',');
				boardRespID = Contents.Substring(11, 7);

				if (parts[4] == "\"SUCCESSFUL in MAP\"")
					successCount++;
				else
					failureCount++;

				x++;
			}
		}
	}
	catch (Exception e){ Add.AddToFile(e.Message.ToString()); }

	return boardLine;
}

Open in new window

0

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

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

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
Suggested Courses

721 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