質問

I've been able to get this code to work:

string[] path = Directory.GetFiles(@"c:\Users\james.krueger\Desktop\Test Folder\");

The problem is this displays the entire path.

This next block of code seems to be what I want. However, it prompts me with the error message that it cannot implicitly convert string to string[].

Any ideas on how to get the file name alone?

string[] path = Path.GetFileName(@"c:\Users\james.krueger\Desktop\Test Folder\");

string[] filePaths = path;
foreach (string element in filePaths)
{
    lb1.Items.Add(element);
}
役に立ちましたか?

解決

You apply the Path.GetFileName to the strings returned by the Directory.GetFiles

private void button2_Click(object sender, EventArgs e) 
{ 
    string[] path = Directory.GetFiles(@"c:\Users\james.krueger\Desktop\Test Folder\");
    foreach (string element in path)
    {
        lb1.Items.Add(Path.GetFileName(element));
    }
}

Path.GetFileName doesn't return the filenames of a directory, but simply extract from a pathname the filename part

However, if your lb1 is a ListBox, you could achieve your result with a very compact code using Linq

string folder = @"c:\Users\james.krueger\Desktop\Test Folder\";
string[] files = Directory.EnumerateFiles(folder).Select(x => Path.GetFileName(x)).ToArray();
lb1.DataSource = files;

他のヒント

Path.GetFileName(@"c:\Users\james.krueger\Desktop\Test Folder\")

returns a string. The compiler is telling you that it cannot assign that to a string[].

Now, what GetFileName does is remove the path part of the name, and return just the file name, so it is only part of the solution. You still need the call to Directory.GetFiles.

So, call Directory.GetFiles and then for each item in the array returned by Directory.GetFiles, call Path.GetFileName(). For example:

foreach (string name in Directory.GetFiles(dirName)
    .Select(path => Path.GetFileName(path)))
{
    lb1.Items.Add(name);
}

Or a perhaps somewhat more efficient version using IEnumerable<string> rather than string[]:

foreach (string name in Directory.EnumerateFiles(dirName)
    .Select(path => Path.GetFileName(path)))
{
    lb1.Items.Add(name);
}

Path.GetFileName() returns a string not string[].

You'll want to use Directory.GetFiles() in place of this.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top