Reputation:
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
Reputation: 28970
File.Copy(file.FullName, outputDir + @"\" + file.Name.Replace(" ", "_"));
Upvotes: 0
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
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