如何从文件路径名中提取文件名?

我需要将所有文件从源文件夹移动到目标文件夹。 如何从文件路径名中轻松提取文件名?

string newPath = "C:\\NewPath"; string[] filePaths = Directory.GetFiles(_configSection.ImportFilePath); foreach (string filePath in filePaths) { // extract file name and add new path File.Delete(filePath); } 

请尝试以下方法:

 string newPathForFile = Path.Combine(newPath, Path.GetFileName(filePath)); 
 Path.GetFileName(filePath) 

使用DirectoryInfo和Fileinfo而不是文件和目录,它们提供了更多高级function。

 DirectoryInfo di = new DirectoryInfo("Path"); FileInfo[] files = di.GetFiles("*.*", SearchOption.AllDirectories); foreach (FileInfo f in files) f.MoveTo("newPath"); 

您可能想尝试FileInfo.MoveTo方法(以下链接中的代码示例):

http://msdn.microsoft.com/en-us/library/system.io.fileinfo.moveto.aspx

你可以这样做:

 string newPath = "C:\\NewPath"; string[] filePaths = Directory.GetFiles(_configSection.ImportFilePath); foreach (string filePath in filePaths) { string newFilePath = Path.Combine(newPath, Path.GetFileName(filePath); File.Move(filePath, newFilePath); }