2010-10-21 35 views
26

Necesito mover todos los archivos de la carpeta fuente a la carpeta de destino. ¿Cómo puedo extraer fácilmente el nombre del archivo del nombre de la ruta del archivo?¿Cómo extraer el nombre del archivo del nombre de la ruta del archivo?

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

Respuesta

49

intente lo siguiente:

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

Gracias, Me encanta este sitio)) 1 min para obtener la respuesta. –

+7

De nada. No tengo nada mejor que hacer de todos modos (ya sabes: trabajo). –

+0

mucha gente a ver su problema :), Inteligencia Colectiva – TalentTuner

10

uso DirectoryInfo y Fileinfo en lugar de archivos y directorios, presentan características más avanzadas.

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

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

Usted puede hacerlo de esta manera:

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