A
A
Artemy Gast2018-05-09 00:42:59
.NET
Artemy Gast, 2018-05-09 00:42:59

C# .Net How to change name and extension in different folder?

I wrote a script to change the name and extension of the file (See below), it converts all these files properly, but the problem is, if there is another folder in the folder and there are other files, then the script cannot access the folder and also change the name and the extension of the files attached there, how to fix this problem? Thank you in advance.
Script C# .Net
int i = 0;
stringname = @"C:\Path";
DirectoryInfo dir = new DirectoryInfo(name);
foreach(var item in dir.GetFiles()){
File.Move (item.FullName, name + "test_" + i.ToString() + ".pp");
i++;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sumor, 2018-05-09
@HEJlbCOH

Something like this, recursively:

string name = @"C:\Путь";
DirectoryInfo dir = new DirectoryInfo (name);
ChangeNameRecursive(dir);

void ChangeNameRecursive(DirectoryInfo dir)
{
  int i = 0;
  foreach(var item in dir.GetFiles())
  {  
    File.Move (item.FullName, name + "test_" + i.ToString() + ".pp");
    i++;
  }
  foreach(var d in dir.GetDirectories())
  {  
    if(d.Name == "." || d.Name == "..") continue;
    ChangeNameRecursive(d);
  }
}

X
xD_Antlion, 2018-05-09
@xD_Antlion

static void ChangeNameRecursive(DirectoryInfo dir)
{
  int i = 0;
  foreach(var item in dir.GetFiles())
  {  
    File.Move (item.FullName, $"{name} test_ {i.ToString()} {".pp"}");
    i++;
  }
  foreach(var d in dir.GetDirectories())
  {  
    if(d.Name == "." || d.Name == "..") 
    {
       continue;
    }
    ChangeNameRecursive(d);
  }
}

Call like this:
private readonly string name = @"C:\Путь";
// const PATH = @"C:\Путь";
ChangeNameRecursive(new DirectoryInfo (name));

A
ApeCoder, 2018-05-13
@ApeCoder

Firstly, there is a special language for scripters - powershell, and on it the task is solved like this:
Secondly, there is a whole article with different ways to bypass nested folders:

  • System.IO.SearchOption.AllDirectories
  • recursion
  • stack or queue for traversing a directory tree in a loop

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question