user1143606
user1143606

Reputation:

Take the space out of file names and or replace character with something else

Im trying to remove the spaces out of a bunch of file names(pdf's in a directory). I have tried the following. both input and output directories are folderbrowserdialog box's

DirectoryInfo di = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
foreach (var file in di.GetFiles())
{
     try
     {
        File.Copy(file.FullName, outputDir + @"\" + file.Replace(" ", "_"));        
     }
}

Upvotes: 0

Views: 5163

Answers (3)

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

File.Copy(file.FullName, outputDir + @"\" + file.Name.Replace(" ", "_"));

Upvotes: 0

Nate
Nate

Reputation: 30636

Try this --

DirectoryInfo di = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
foreach (var file in di.GetFiles())
{
    try
    {
        File.Copy(file.FullName, Path.Combine(outputDir, Path.GetFileName(file.FullName).Replace(" ", "_")));
    }
    catch { }
}

Upvotes: 0

Guffa
Guffa

Reputation: 700182

Get the file name out of the file info object:

file.Name.Replace(" ", "_")

Use Path.Combine to put the path together (more robust across different systems):

Path.Combine(outputDir, file.Name.Replace(" ", "_"))

So:

di = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
foreach (var file in di.GetFiles()) {
  try {
    File.Copy(file.FullName, Path.Combine(outputDir, file.Name.Replace(" ", "_")));                     
  }

Upvotes: 7

Related Questions