Batch renaming files C# - c#

I have a unity project that i need to rename basically all my files in it to contain a - as a way of easily identifying what assetbundle i need to load it from.
I would need to insert a - at the end of the identifier so for example, testtest.png would become test-test.png and so on.
I currently have this (just want to get the identifier from the file name itself for now) however, the first string in temp is always empty with the second one containing the rest of the file name
foreach (string file in Directory.GetFiles(Directory.GetCurrentDirectory()))
{
string name = file.Split('\\').Last();
if (name.StartsWith(args[0]))
{
string[] temp = name.Split(new[]{args[0]},StringSplitOptions.None);
foreach (string s in temp)
{
Console.WriteLine(s);
}
}
}
D:\renamething\bin\Debug>renamething.exe test
.pdb
I tried Regex for it as well however it produced the same result, empty string in the first one, rest of it in the second.

I don't think that would work, especially the args[0]
Try this:
foreach (string file in Directory.GetFiles(Directory.GetCurrentDirectory()))
{
var fileInfo = new FileInfo(file); //Get FileInfo
if (!fileInfo.Name.StartsWith(args[0], StringComparison.OrdinalIgnoreCase)) //If File doesn't start with the specified arguments, don't process
{
continue;
}
//Consider file -> C:/TestFolder/test.png
var directory = fileInfo.DirectoryName;//Gives C:\TestFolder\
var extension = fileInfo.Extension; //gives ".png"
var fileName = Path.GetFileNameWithoutExtension(fileInfo.Name); //Gives "test"
var modifiedFileName = $"{fileName}-test{extension}"; //Gives "test-test.png
var modifiedFullPath = $"{directory}/{modifiedFileName}";// C:\TestFolder\test-test.png
fileInfo.MoveTo(modifiedFullPath);
}

With the code from #Zee (and #Dai from having a second look over), here is what i ended up in the odd chance that anyone else in the future comes here and needs it
public static void Main(string[] args){
foreach(string file in Directory.GetFiles(Directory.GetCurrentDirectory())){
FileInfo fileInfo=new FileInfo(file);
if(fileInfo.Name.StartsWith(args[0])&&fileInfo.Name.EndsWith(".png"){
string[]temp=Regex.Split(fileInfo.Name, #"(?<!^)(?=[A-Z])");
temp[0]+="-";
File.Move(fileInfo.FullName,String.Concat(temp));
}
}
}

Related

Ignore Empty files C#

I am trying to avoid empty files in my Program and the way i am doing it doesnt work.
I got a machschine that create logs, at Weekend is nobody here and but the maschine create a file with only 5,6 lines, the right one should have 20k lines.
I know there is FileInfo.Length but i dont know how to use it with this what a have right now.
public List<SystemLogFileData> ProcessSystemLogFiles(List<string> systemLogsFilePaths)
{
List<SystemLogFileData> systemLogFilesData = new List<SystemLogFileData>();
foreach (var filePath in systemLogsFilePaths)
{
string[] lines = System.IO.File.ReadAllLines(filePath);
var systemLogFileData = ProcessSystemLogFile(lines.ToList());
if (File.ReadAllText(systemLogFileData).Length > 100)
{
systemLogFilesData.Add(systemLogFileData);
}
}
return systemLogFilesData;
}
I solved it and it works well. Not in my main Program but in Autobackup.
insted of ignoring the the not important file i don't copy them and i reached my goal.
Thakns for the help!
//path of file
string pathToOriginalFile = #"C:\Users\Desktop\c#\Logging\Systemlog.bk66";
//duplicate file path
string PathForDuplicateFile = #"C:\\\Desktop\c#\Systemlog";
//rename fileName if Exists
FixFileName(ref PathForDuplicateFile, ".bk");
if (File.ReadAllText(pathToOriginalFile).Length > 2000)
{
File.Copy(pathToOriginalFile, PathForDuplicateFile);
}
else
{
}
//provide source and destination file paths

How to create a loop using values from appSettings in my console application

Since I'm new in C# I need some help.
In my console application, in App.config I added a key which contains 2 paths(as seen below).
<appSettings>
<add key="myPath" value="D:\APPS\Sys\ARS\Db, C:\APPS\Sys\ARS\Lg" />
</appSettings>
What I would like to do is, to create a method which loops through these paths, search if the following files exist respectively for D:\...: error.log and for C:\...: errtier0.log.
Finally to return the full path with the file included, e.g. D:\APPS\Sys\ARS\Db\error.log.
Thank you in advance
What I did so far is,
In the beginning I created 2 different keys, one for each path, and I had 2 methods (see the one below) which were searching for each file in the key path.
public static string findRemedy()
{
string myRemedyPath = ConfigurationManager.AppSettings["myRemedyPath"];
DirectoryInfo remedyPath = new DirectoryInfo(myRemedyPath);
foreach (var remedy in remedyPath.GetFiles("error.log"))
{
return remedy.Name;
}
return "";
}
Afterwards, I was parsing the value in another method in which I was adding the name of the file in the path
public static string findPath()
{
string fileRem = findRemedy();
string Rpath = #"D:\APPS\Sys\ARS\Db\" + fileRem;
return Rpath;
}
Read the setting in to a string, split it and try to open a file at each path. Return the first one that works
string appSetting = ConfigurationManager.AppSettings["myPath"];
string[] paths = appSetting.Split[','];
foreach(string path in paths){
//Check if file exists by appending the file name to end of path
//and attempting to open the file
//If successful return path, if not return null
}
string myPath = ConfigurationManager.AppSettings["myPath"];
string[] parts = myPath.Split(',');
foreach (string part in parts)
{
//do what you want
}

Crawling a directory

I have this test path:
private static string dCrawler = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "TestLetters";
Is there a way to say:
foreach (item in dCrawler)
{
if (item.isFile)
{
// check file info date modified code
} else
{
foreach (fileinfo file in ...
}
}
so far I have only found ways to check a file in a directory. Is the only way to do it by having two separate loops one for files and one for folders?
You can use Directory.GetFiles(); that returns a string[] and use the string value to create your FileInfo. Like this
foreach (string n in Directory.GetFiles(dCrawler))
{
FileInfo b = new FileInfo(n);
}
To get directories, you can similarly use Directory.GetDirectories();
foreach (string n in Directory.GetDirectories(dCrawler))
{
DirectoryInfo b = new DirectoryInfo(n);
}

Getting name(s) of FOLDER containing a specific SUBSTRING from the C:Temp directory in C#

Guys as the title says it I have to get the names of FOLDERS having a particular (user indicated) sub string.
I have a text box where the user will input the wanted sub string.
and I am using the codes below to achieve my goal.
string name = txtNameSubstring.Text;
string[] allFiles = System.IO.Directory.GetFiles("C:\\Temp");//Change path to yours
foreach (string file in allFiles)
{
if (file.Contains(name))
{
cblFolderSelect.Items.Add(allFiles);
// MessageBox.Show("Match Found : " + file);
}
else
{
MessageBox.Show("No files found");
}
}
It does not work.
When I trigger it,only the message box appears.
Help ?
You can use the appropriate API to let the framework filter the directories.
var pattern = "*" + txtNameSubstring.Text + "*";
var directories = System.IO.Directory.GetDirectories("C:\\Temp", pattern);
Because the MessageBox will appear for the first path that does not contain the substring
You could use Linq to get the folders, but you will need to use GetDirectories not GetFiles
string name = txtNameSubstring.Text;
var allFiles = System.IO.Directory.GetDirectories("C:\\Temp").Where(x => x.Contains(name));//
if (!allFiles.Any())
{
MessageBox.Show("No files found");
}
cblFolderSelect.Items.AddRange(allFiles);
You don't want to have the message box inside the loop.
string name = txtNameSubstring.Text;
string[] allFiles = System.IO.Directory.GetFiles("C:\\Temp");//Change path to yours
foreach (string file in allFiles)
{
if (file.Contains(name))
{
cblFolderSelect.Items.Add(file);
// MessageBox.Show("Match Found : " + file);
}
}
if(cblFolderSelect.Items.Count==0)
{
MessageBox.Show("No files found");
}
(Assuming cblFolderSelect was empty before this code runs)
As you currently have it, you're deciding whether to show the message box for each file that you examine. So if the first file doesn't match, you'll be told "No files found" even though the next file might match.
(I've also changed the Add to add the individual file that matches, not all of the files (for which one or more matches))

how to read all the subdirectories in a given destination which contain Master File in it

I am having a problem .
My Problem is to read all the subdirectories in a given destination which contain Master file .
I can read subdirectories but i am creating a project which only read given directory which should contain Master file in the directory .
In the given directory a file called Master file should be there.
I want to write the code like if the given directory doesnot contain any Master file in it it should Jump to another Directory.
My source Directory is #"C:\test.
In #"C:\test" there are many folders and subfolders .
the test directory contains "C:\test\test1\test2\test3 . In this path test3 folder contains Master file test1 and test2 doesn't .
I want to write this code something like this,
MLMReader Reader = new MLMReader();
Reader.OpenDirectory(#"C:\test");
if (!File.Exists(test + "\\Master"))
{
//i want to loop the "C"\\" and if test1 does not contain
// Master File then jump to another directory test2, if
//test2 directory contain Master File then the work should
// continue after finishing go to test3
}
Is there any way to do .
Any suggestions for my problem.
I haven't tested, but I'm pretty sure the following will work:
string[] paths = Directory.GetFiles(dirPath, "MasterFile", SearchOption.AllDirectories);
Then you can just foreach over the resulting array, if you want to go through all MasterFiles. Or if you just care about the first result, then it's just paths[0] -- of course, means it does a lil bit extra work finding all matching paths. And you probably don't need a check for an empty array as an index out of bounds would indicate there's no MasterFile (unless you want to catch that and then rethrow as file not found exception or whatever).
Linq-to-FileSystem allows you to perform structured queries on your file system. See the following example:
var dir = new DirectoryInfo(#"C:\test");
// find all subdirectories of test that contains a file / folder called 'Master'
var dirs = dir.Elements()
.Where(d => d.Elements().Any(i => i.Name == "Master"))
this is my code where I program with directorys, hope it will help you.
using System;
using System.IO;
static void Print(string path, int? rec, int? tree, bool color, int? level = 0)
{
if ((rec != null && level > rec) || path == null) return;
if (rec == null) rec = 0;
string[] dir;
string[] fil;
try
{
dir = Directory.GetDirectories(path);
fil = Directory.GetFiles(path);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
return;
}
foreach (string s in dir)
{
WriteSpace(level,tree);
Console.WriteLine(s);
Print(s, rec, tree, color, level + 1);
}
if (color)
{
ConsoleColor def = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Blue;
foreach (string s in fil) // vypis file
{
WriteSpace(level, tree);
Console.WriteLine(s);
}
Console.ForegroundColor = def;
}
else
{
foreach (string s in fil)
{
WriteSpace(level, tree);
Console.WriteLine(s);
}
}
}
private static void WriteSpace(int? level, int? tree)
{
for (int i = 0; i < level*tree; i++)
Console.Write(" ");
}
}
Here's a Recursive Example on how you can traverse a directory structure and look for a certain file, once it is found you can call the corresponding method.
static void Main()
{
TraverseDirectory(#"D:\TestDirectory");
}
static void DoSomethingWithMaster(string path)
{
Console.WriteLine("Found master at {0}", path);
}
static void TraverseDirectory(string directory)
{
var currentDirectory = new DirectoryInfo(directory);
foreach(var dir in currentDirectory.GetDirectories())
{
var currentPath = dir.FullName;
TraverseDirectory(currentPath);
var pathToMasterFile = Path.Combine(currentPath, "Master");
if (File.Exists(pathToMasterFile))
DoSomethingWithMaster(pathToMasterFile);
}
}
I have the following Folder Structure:
D:\TestDirectory\1
D:\TestDirectory\2
D:\TestDirectory\3
D:\TestDirectory\4
D:\TestDirectory\4\Master
D:\TestDirectory\5
And when running the above it prints: Found master at D:\TestDirectory\4
All you need for this is:
using System;
using System.IO;
You can also move TraverseDirectory(currentPath); to the end of the foreach-loop, where you put it depends on when you want to detect the file, do you want to go deep and then climb your way back and check for the Master-file on the way up, or do you want to check for the master file before you enter the next directory?
According to your question, you might want to swap them in my answer and if I understand you correctly, you might not even want to go to the next directory after finding one master-file?
foreach(var dir in currentDirectory.GetDirectories())
{
var currentPath = dir.FullName;
var pathToMasterFile = Path.Combine(currentPath, "Master");
if (File.Exists(pathToMasterFile))
DoSomethingWithMaster(pathToMasterFile);
TraverseDirectory(currentPath);
}
In this example, it does exactly what you are saying in your commented code inside your if. It will first check TestDirectory\1 for a Master file and then go further down the line. If you don't care about any other Master-files in one sub-directory once it is found, you can just nest TraverseDirectory(pathToMasterFile) inside an else-block.
Edit
You might want to use EnumerateDirectories, see MSDN for details.

Categories

Resources