convert filename to string c #

0

Good morning, requesting your help to know how to get the name of a file by means of C # and save the name in a variable, that is to say in a certain route I have the file Example1.txt, I have to enter that route and get the name of the file without declaring it previously and then that name save it in a variable of type string.

It would be something like this, but with the difference that in the result line the variable path will be passed.

string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string result;

result = Path.GetFileName(fileName);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    fileName, result);

result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    path, result);
    
asked by Alberto Arenas 22.06.2017 в 18:23
source

1 answer

1

You could do a Split('\') to separate the route and take the last element:

string[] pathSplit = path.Split('\');
string name = pathSplit[pathSplit.Count - 1];

or you could use FileInfo :

FileInfo info = new FileInfo(path);
string name = info.Name;
    
answered by 22.06.2017 в 18:27