skip to Main Content

I am using C# in Visual Studio 2022 and am trying to get a file name out of a specific folder.

The path to the folder is "C:UsersUserPicturesTest" and there is just one .png file in it.

when I use the following code:

string path = Path.GetFileName(path:@"C:UsersUserPicturesTest");

//result = Path.GetFileName(fileName);
Console.WriteLine(path);

It just returns a blank line. I was expecting the file name.

I will eventually have a number of files in the folder and will want to obtain those too.

2

Answers


  1. For read files in folders use this code:

    var path = Directory.GetFiles(@"C:UsersUserPicturesTest");
    
    foreach(var item in path)
    {
        Console.WriteLine(item);
    }
    
    Login or Signup to reply.
  2. The Path.GetFileName()method takes a string as an argument which is supposed to be a relative or full path to a file. It simply cuts the input string and returns only the file name. It does not read folders for you.

    To read files of folders, refer to Felipe’s answer. Directory.GetFiles(path/to/folder)will give you an array of (full) paths to the files in that folder. If you expect only a single file to be in a folder you can just use linq and combine the two methods like this:

    var filename = Path.GetFileName(Directory.GetFiles("path/to/folder").First());

    This will get you the filename of the first (or only) file in the folder "path/to/folder". If it could be empty you should of course handle that scenario too

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search