user3516183
user3516183

Reputation: 71

Extracting File name from a Foreach of a OpenFileDialog in c#

Ok I am sure the answer is real easy. But here goes.

foreach (String file in openFileDialog1.FileNames)
{
    dm.UploadFile(DMIDENTITY, file, Path.GetExtension(openFileDialog1.FileName), Path.GetFileName(openFileDialog1.FileName));
    // for dev only..  MessageBox.Show(Path.GetFileName(openFileDialog1.FileName));
}

It loops through the multiple files with their respective paths fine, but they are also being put into a database as a linked reference. I need JUST the file name not the entire path. Doing it this way however only allows for the first file name to be recognised, and it then puts that in however many times there is a file.

Like I said I am sure its a simple one. But I thought I would propose it to the magical internet wizards of StackOverflow :)

Upvotes: 1

Views: 1954

Answers (1)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

Looping over all the selected files is correct. However, you're not using the file name of the current loop iteration in all places, but extract extension and file name from the FileName property - this is of course wrong.

You need to reference the current loop iteration's file name in all places where you reference the file name:

foreach (String file in openFileDialog1.FileNames)
{
    dm.UploadFile(DMIDENTITY, file, Path.GetExtension(file), Path.GetFileName(file));
    // for dev only..  MessageBox.Show(Path.GetFileName(file));
}

Upvotes: 3

Related Questions