2010-10-21 51 views
26

Tôi cần di chuyển tất cả các tệp từ thư mục nguồn sang thư mục đích. Làm cách nào tôi có thể dễ dàng trích xuất tên tệp từ tên đường dẫn tệp?Cách trích xuất tên tệp từ tên đường dẫn tệp?

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

Trả lời

49

Hãy thử như sau:

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

Cảm ơn, Tôi yêu trang web này)) 1 phút để có được câu trả lời. –

+7

Bạn được chào đón. Không có gì tốt hơn để làm anyway (bạn biết: công việc). –

+0

nhiều người xem vấn đề của bạn :), Thông minh tập thể – TalentTuner

10

sử dụng DirectoryInfo và FileInfo thay vì File và Directory, họ giới thiệu các tính năng nâng cao hơn.

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

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

Bạn thể làm điều đó như thế này:

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); 
} 
Các vấn đề liên quan