2

I seem to be having a problem with C# 2008. I am creating a simple program that shows a list of all the files within a specific folder. I chose to experiment with system files in the Windows folder. It shows a list of the files and then an exception occurs. Here is the code:

if (EnterNumber == "1")
{
    Console.WriteLine("Files");
    DirectoryInfo folderInfo = new DirectoryInfo("F:\\WINDOWS");
    FileInfo[] Files = folderInfo.GetFiles();

    String UserChoice = Console.ReadLine();


    for (int index = 0; index < Files.Length; index++)
    {


        Console.WriteLine("{0}, {1} ({2})", index++, Files[index].Name, Files[index].Length);
    }
    Console.Write("Return To Main Menu?: ");
    if (UserChoice == "y")
    { 

So the user presses the number 1 to show the files and they appear in a list. It displays the files in the Windows folder. But can you see the console write line with several pieces of information? A line appears with a message to an error. The exception occurs saying that the index is outside the bounds of the array. I know what an array is, but I have a problem applying that information. If you can tell me of a way to remove this error then I would be grateful. So the files show normally, no matter how long the list is. Also, is there a way to allow the user to clear the screen and return to the main menu? I have tried the clear function, but should I keep adding the if statements that allow the user to input their choice again?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
user1146468
  • 21
  • 1
  • 3

2 Answers2

3
        for (int index = 0; index < Files.Length; index++)
        {
            Console.WriteLine("{0}, {1} ({2})", index++, Files[index].Name, Files      [index].Length);
        }

The problem is in your writeline, you are incrementing index again. I would just change it to index and not index++.

nmjohn
  • 1,432
  • 7
  • 16
2

Try changing:

Console.WriteLine("{0}, {1} ({2})", index++, Files[index].Name, Files[index].Length);

to:

Console.WriteLine("{0}, {1} ({2})", index, Files[index].Name, Files[index].Length);

The ++ operator (MSDN documentation) is being incremented twice in your loop, when you probably only want to go one at a time.

utopianheaven
  • 1,267
  • 7
  • 18
  • This is correct, the second i++ on the Console.WriteLine() section within the for loop will always increment index out of the bounds of the Files array on the last iteration. – acm Jan 12 '12 at 21:48