2010-10-21 9 views
26

Je dois déplacer tous les fichiers du dossier source vers le dossier de destination. Comment puis-je facilement extraire le nom du fichier à partir du nom du chemin du fichier?Comment extraire le nom du fichier à partir du nom du chemin du fichier?

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

Répondre

49

les opérations suivantes:

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

Merci, J'adore ce site)) 1 min pour avoir la réponse. –

+7

De rien. Rien de mieux à faire de toute façon (tu sais: travail). –

+0

beaucoup de gens pour voir votre problème :), Intelligence Collective – TalentTuner

10

utilisation DirectoryInfo et Fileinfo au lieu de répertoires et fichiers, ils présentent des fonctionnalités plus avancées.

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

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

Vous pouvez le faire comme ceci:

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