Reputation: 1103
I have over 1000 files in a folder with names like abc_1, abc_2 ... abc_n
I want to delete this prefix 'abc_' from all the files. Any chance to not doing this manually because there are over 1000, and it will be a pain.
How can do this with c# ?
Upvotes: 43
Views: 106184
Reputation: 28970
You can try with this code
DirectoryInfo d = new DirectoryInfo(@"C:\DirectoryToAccess");
FileInfo[] infos = d.GetFiles();
foreach(FileInfo f in infos)
{
File.Move(f.FullName, f.FullName.Replace("abc_","")); // Careful!! This will replaces the text "abc_" anywhere in the path, including directory names.
}
Upvotes: 107
Reputation: 52366
Use this if you want all directories recursively:
using System;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
foreach (String filePath in Directory.GetFiles(@"C:\folderName\", "*.*", SearchOption.AllDirectories))
{
File.Move(filePath, filePath.Replace("abc_", ""));
}
}
}
}
Upvotes: 2
Reputation: 8396
This command would do the trick, using renamer:
$ renamer --find "abc_" *
Upvotes: -3
Reputation: 114
This code enables user to replace a part of file name. Useful if there are many files in a directory that have same part.
using System;
using System.IO;
// ...
static void Main(string[] args)
{
FileRenamer(@"D:\C++ Beginner's Guide", "Module", "PDF");
Console.Write("Press any key to quit . . . ");
Console.ReadKey(true);
}
static void FileRenamer(string source, string search, string replace)
{
string[] files = Directory.GetFiles(source);
foreach (string filepath in files)
{
int fileindex = filepath.LastIndexOf('\\');
string filename = filepath.Substring(fileindex);
int startIndex = filename.IndexOf(search);
if (startIndex == -1)
continue;
int endIndex = startIndex + search.Length;
string newName = filename.Substring(0, startIndex);
newName += replace;
newName += filename.Substring(endIndex);
string fileAddress = filepath.Substring(0, fileindex);
fileAddress += newName;
File.Move(filepath, fileAddress);
}
string[] subdirectories = Directory.GetDirectories(source);
foreach (string subdirectory in subdirectories)
FileRenamer(subdirectory, search, replace);
}
Upvotes: 1
Reputation: 11
I like the simplicity of the answer with the most up-votes, but I didn't want the file path to get modified so I changed the code slightly ...
string searchString = "_abc_";
string replaceString = "_123_";
string searchDirectory = @"\\unc\path\with\slashes\";
int counter = 0;
DirectoryInfo d = new DirectoryInfo(searchDirectory);
FileInfo[] infos = d.GetFiles();
foreach(FileInfo f in infos)
{
if (f.Name.Contains(searchString))
{
File.Move(searchDirectory+f.Name, searchDirectory+ f.Name.Replace(searchString, replaceString));
counter++;
}
}
Debug.Print("Files renamed" + counter);
Upvotes: 1
Reputation: 10306
Following code will work, not tested though,
public class FileNameFixer
{
public FileNameFixer()
{
StringToRemove = "_";
StringReplacement = "";
}
public void FixAll(string directory)
{
IEnumerable<string> files = Directory.EnumerateFiles(directory);
foreach (string file in files)
{
try
{
FileInfo info = new FileInfo(file);
if (!info.IsReadOnly && !info.Attributes.HasFlag(FileAttributes.System))
{
string destFileName = GetNewFile(file);
info.MoveTo(destFileName);
}
}
catch (Exception ex)
{
Debug.Write(ex.Message);
}
}
}
private string GetNewFile(string file)
{
string nameWithoutExtension = Path.GetFileNameWithoutExtension(file);
if (nameWithoutExtension != null && nameWithoutExtension.Length > 1)
{
return Path.Combine(Path.GetDirectoryName(file),
file.Replace(StringToRemove, StringReplacement) + Path.GetExtension(file));
}
return file;
}
public string StringToRemove { get; set; }
public string StringReplacement { get; set; }
}
you can use this class as,
FileNameFixer fixer=new FileNameFixer();
fixer.StringReplacement = String.Empty;
fixer.StringToRemove = "@@";
fixer.FixAll("C:\\temp");
Upvotes: 4
Reputation: 460028
You can use File.Move
and String.Substring(index)
:
var prefix = "abc_";
var rootDir = @"C:\Temp";
var fileNames = Directory.EnumerateFiles(rootDir, prefix + "*", SearchOption.AllDirectories);
foreach(String path in fileNames)
{
var dir = Path.GetDirectoryName(path);
var fileName = Path.GetFileName(path);
var newPath = Path.Combine(dir, fileName.Substring(prefix.Length));
File.Move(path, newPath);
}
Note: Directory.EnumerateFiles(rootDir, prefix + "*", SearchOption.AllDirectories);
will search also subfolders from your root directory. If this is not intended use SearchOption.TopDirectoryOnly
.
Upvotes: 13
Reputation: 2666
string path = @"C:\NewFolder\";
string[] filesInDirectpry = Directory.GetFiles(path, "abc*");
forearch(string file in filesInDirectory)
{
FileInfo fileInfo = new FileInfo(file);
fileInfo.MoveTo(path + "NewUniqueFileNamHere");
}
Upvotes: 1
Reputation: 3283
You should have a look at the DirectoryInfo class and GetFiles() Method. And have a look at the File class which provides the Move() Method.
File.Move(oldFileName, newFileName);
Upvotes: 3
Reputation: 45071
Total Commander has the possibility to rename multiple files (You don't need to program a tool on your own for each little task).
Upvotes: 1
Reputation: 5042
You can enumerate the file.
using System.IO;
string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
Then, ForEach the string[] and create a new instance of the IO.File
object.
Once you get a handle on a File, just call the Move method and pass in String.Replace("abc_", String.Empty).
I said Move because there is no direct Rename method in IO.File.
File.Move(oldFileName, newFileName);
Be mindful of the extension.
Upvotes: 3
Reputation: 5801
you can use a foreach iteration along with the File class from the System.IO namespace.
All its methods are provided for you at no cost here: http://msdn.microsoft.com/en-us/library/system.io.file%28v=vs.100%29.aspx
Upvotes: 1