2010-10-21 141 views
26

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

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); 
} 

回答

49

尝试以下操作:

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

谢谢,我喜欢这个网站))1分钟得到答案。 – 2010-10-21 10:38:23

+7

不客气。无论如何没有更好的办法(你知道:工作)。 – 2010-10-21 10:39:57

+0

很多人看到你的问题:),集体智慧 – TalentTuner 2010-10-21 10:40:27

10

使用的DirectoryInfo和Fileinfo的,而不是文件和目录,他们目前更先进的功能。

DirectoryInfo di = 
    new DirectoryInfo("Path"); 
FileInfo[] files = 
    di.GetFiles("*.*", SearchOption.AllDirectories); 

foreach (FileInfo f in files) 
    f.MoveTo("newPath"); 
4

你可以这样说:

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); 
}