-2

I use the following code to take all the files from a directory and search for a specific file:

string [] fileEntries = Directory.GetFiles("C:\\uploads");
foreach(string fileName in fileEntries)
    if (fileName.Contains(name))
        PicturePath = fileName;

where "name" is a string which I get from DB.

It seems to work to an extend but if my file contains a space in fileName it only takes the first string from fileName which is the first string before the white space, ignoring th rest. How can i take the full fileName (as well as the path to that file accordingly).

For example: I have a file named "ALEXANDRU ALINA.jpg" inside uploads and in name i have the string "ALEXANDRU ALINA". When I run that code (writing the PicturePath) it displays just "ALEXANDRU".

Radu Stanescu
  • 37
  • 1
  • 3
  • 10
  • 2
    What do you mean by "it only takes the first string"? A short but complete program, with sample input, expected output and actual output, would make this *much* clearer. – Jon Skeet Feb 04 '15 at 13:27
  • Edited my question. Hopefully it is clear now – Radu Stanescu Feb 04 '15 at 13:32
  • Not really - we don't know how you're displaying it, or anything like that. `Directory.GetFiles()` *will* give full filenames, including spaces... – Jon Skeet Feb 04 '15 at 13:41

1 Answers1

0

This might be what you're looking for:

string[] fileEntries = Directory.GetFiles("C:\\uploads");

foreach (string fileName in fileEntries)
{
    FileInfo fi = new FileInfo(fileName);
    if (fi.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase)) PicturePath = fileName;
}

What you're attempting to do is find the target file name within the whole path, but the method you're using could produce errors (what if the name is contained within part of the folder path?). By using the System.FileInfo class and its Name property, which is the file name only (not the full file path which includes the containing folder path), you won't be needlessly searching any part of the folder path.

rory.ap
  • 34,009
  • 10
  • 83
  • 174