在开发使用C#可以是台式机或Web的应用程序时,会出现这种从给定路径提取文件名的要求(在使用“文件打开”对话框或任何其他来源选择文件时可以采用该路径)。路径可以包含驱动器名称,目录名称和文件名。要从文件中提取文件名,我们使用“ Path ”类的“ GetFileName() ”方法。此方法用于获取指定路径字符串的文件名和扩展名。返回值为null如果文件路径为空。
Syntax: public static string GetFileName (string path);
Here, path is the string from which we have to obtain the file name and extension.
Return Value: This method will return the characters after the last directory separator character in path. If the last character of the path is a directory or volume separator character, this method returns Empty. If the path is null, this method returns null.
异常:如果路径包含GetInvalidPathChars()中定义的一个或多个无效字符,则此方法将提供ArgumentException 。
例子:
Input :
string strPath = "c://myfiles//ref//file1.txt";
//function call to get the filename
filename = Path.GetFileName(strPath);
Output :
file1.txt
// C# program to extract the
// filename from a given path
using System;
using System.IO;
using System.Text;
namespace Geeks {
class GFG {
// Main Method
static void Main(string[] args)
{
// taking full path of a file
string strPath = "C:// myfiles//ref//file1.txt";
// initialize the value of filename
string filename = null;
// using the method
filename = Path.GetFileName(strPath);
Console.WriteLine("Filename = " + filename);
Console.ReadLine();
}
}
}
Filename = file1.txt
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.io.path.getfilename?view=netframework-4.7.2