Captain Comic
Captain Comic

Reputation: 16186

How to extract file name from file path name?

I need to move all files from source folder to destination folder. How can I easily extract file name from file path name?

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

Upvotes: 29

Views: 71515

Answers (5)

TalentTuner
TalentTuner

Reputation: 17556

Path.GetFileName(filePath)

Upvotes: 48

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120917

You can do it like this:

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

Upvotes: 4

dhirschl
dhirschl

Reputation: 2098

You may want to try the FileInfo.MoveTo method (code example at the following link):

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

Upvotes: 5

vaitrafra
vaitrafra

Reputation: 662

use DirectoryInfo and Fileinfo instead of File and Directory, they present more advanced features.

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

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

Upvotes: 10

Pieter van Ginkel
Pieter van Ginkel

Reputation: 29632

Try the following:

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

Upvotes: 54

Related Questions