Bari
Bari

Reputation: 75

Adding data the a 2D Array inside for loop

i want to make a simple app that lists all files in a folder in a listview column and the sub directory path is another column. to do this i created a 2D array and tried to add the file name to the first column and the path to the other one. this is my code

  {
        string pathtoList;
        string fileName;
        string DirName;

        pathtoList = (@"D:\Videos");
        string[] allFileNames = System.IO.Directory.GetFiles(pathtoList, "*.*", System.IO.SearchOption.AllDirectories);
        string[,] call1= new string[allFileNames.Length,2];
        for (int i = 0; i< allFileNames.Length; i++)
        {
            fileName = System.IO.Path.GetFileNameWithoutExtension(allFileNames[i].ToString());
            DirName = System.IO.Path.GetDirectoryName(allFileNames[i].ToString());
            call1[0, i] = fileName;
            call1[1, i] = DirName;
        }
    }

when i doe this i get the exception 'Index was outside the bounds of the array.' can anybody tell what is the wrong in this cod? thanks

Upvotes: 0

Views: 40

Answers (2)

ddfra
ddfra

Reputation: 2565

You switched the indexes, this should work:

 {
        string pathtoList;
        string fileName;
        string DirName;

        pathtoList = (@"D:\Videos");
        string[] allFileNames = System.IO.Directory.GetFiles(pathtoList, "*.*", System.IO.SearchOption.AllDirectories);
        string[,] call1= new string[allFileNames.Length,2];
        for (int i = 0; i< allFileNames.Length; i++)
        {
            fileName = System.IO.Path.GetFileNameWithoutExtension(allFileNames[i].ToString());
            DirName = System.IO.Path.GetDirectoryName(allFileNames[i].ToString());
            call1[i, 0] = fileName; // or leave it as it was before and declare string[,] call1= new string[2, allFileNames.Length];
            call1[i, 1] = DirName; //same as above
        }
    }

Upvotes: 1

HOLz1919
HOLz1919

Reputation: 88

You declared Array

[allFileNames.Length,2]

Then you switched indexes, It`s a solution

call1[i, 0] = fileName;
call1[i, 1] = DirName;

Upvotes: 1

Related Questions