Ash
Ash

Reputation: 9061

List the contents of a file on the form in C#?

I was just wondering how do you display the conetnts of a chosen folder on a ListView or something for example so the files can be individually be selected (and multiple files)

At the moment i have a folder dialog where the user chooses their desired path and yeah have stopped there :S

Upvotes: 0

Views: 309

Answers (5)

BillW
BillW

Reputation: 3425

I'm going to focus on your statement : "a Listview or something," and talk about the "something" scenario :)

Why aren't you using the built-in control 'OpenFileDialog : you can set the 'MultiSelect property to 'true and select all the files you like, you can filter the files that appear in complex ways, etc. : it's there, it's "free," it works.

If you specifically do not want to use this control for reasons like, for example, you want the list files to remain visible (i.e., not to be a modal interface) at all times, I suggest you clarify your original question to reflect that. The more you tell us exactly what you want, the more focused the answers you can get.

regards Bill,

Upvotes: 2

Ta01
Ta01

Reputation: 31610

All the cool kids use Linq :)

  var fileList = new DirectoryInfo(@"C:\").GetFiles().Where(file => file.Extension == ".txt");
        foreach (var file in fileList)
        { 
            // Do what you will here
           // listView1.Items.Add(
        }

This just gets text files in the C:\ drive, but you can tweak as necessary

Upvotes: 0

scottm
scottm

Reputation: 28703

If you just call ListView.Items.AddRange(Directory.GetFiles(@"c:\temp"); the names of all files in c:\temp will be shown in the ListView.

Upvotes: 0

Adriaan Stander
Adriaan Stander

Reputation: 166346

Given the string path you can use

Directory.GetDirectories

and

Directory.GetFiles

to retrieve the contents of a folder.

Upvotes: 2

Jrud
Jrud

Reputation: 830

System.IO.Directory.GetFiles(<filepath>)

will return a string array which you can iterate through and display file names. It can be passed a true boolean value as well if you wish to do a recursive directory search.

If you wish to display directories as well, you will need to use

System.IO.Directory.GetDirectories(<filepath>)

Upvotes: 0

Related Questions