Adding a number suffix when creating a folder in C #

I try to process if the folder that I want to create already exists .. to add a number to the folder name .. for example, windows explorer .. for example (New folder, New folder 1, New folder 2 ..) how can I do it's recursive I know this code is wrong. How can I fix or change the code below to solve the problem?

int i = 0; private void NewFolder(string path) { string name = "\\New Folder"; if (Directory.Exists(path + name)) { i++; NewFolder(path + name +" "+ i); } Directory.CreateDirectory(path + name); } 
+4
source share
4 answers

You don’t need recursion for this, but instead you need to look for an iterative solution

 private void NewFolder(string path) { string name = @"\New Folder"; string current = name; int i = 0; while (Directory.Exists(Path.Combine(path, current)) { i++; current = String.Format("{0} {1}", name, i); } Directory.CreateDirectory(Path.Combine(path, current)); } 
+5
source
  private void NewFolder(string path) { string name = @"\New Folder"; string current = name; int i = 0; while (Directory.Exists(path + current)) { i++; current = String.Format("{0} {1}", name, i); } Directory.CreateDirectory(path + current); } 

loan for @JaredPar

+1
source

The easiest way to do this:

  public static void ebfFolderCreate(Object s1) { DirectoryInfo di = new DirectoryInfo(s1.ToString()); if (di.Parent != null && !di.Exists) { ebfFolderCreate(di.Parent.FullName); } if (!di.Exists) { di.Create(); di.Refresh(); } } 
+1
source

You can use this DirectoryInfo extender:

 public static class DirectoryInfoExtender { public static void CreateDirectory(this DirectoryInfo instance) { if (instance.Parent != null) { CreateDirectory(instance.Parent); } if (!instance.Exists) { instance.Create(); } } } 
+1
source

Source: https://habr.com/ru/post/1393629/


All Articles