在C#中创建文件夹时添加数字后缀
本文关键字:添加 数字 后缀 文件夹 创建 | 更新日期: 2023-09-27 18:21:53
我正在尝试处理我想要创建的文件夹是否已经存在。。在文件夹名称中添加数字。。像windows资源管理器。。例如(新文件夹、新文件夹1、新文件夹2..)我怎么能递归地做我知道这个代码是错误的。如何修复或更改下面的代码来解决问题?
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);
}
为此,您不需要递归,而是应该寻找迭代解决方案:
private void NewFolder(string path) {
string name = @"'New Folder";
string current = name;
int i = 1;
while (Directory.Exists(Path.Combine(path, current))) {
i++;
current = String.Format("{0}{1}", name, i);
}
Directory.CreateDirectory(Path.Combine(path, current));
}
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);
}
@JaredPar 的信用
最简单的方法是:
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();
}
}
您可以使用此DirectoryInfo扩展程序:
public static class DirectoryInfoExtender
{
public static void CreateDirectory(this DirectoryInfo instance)
{
if (instance.Parent != null)
{
CreateDirectory(instance.Parent);
}
if (!instance.Exists)
{
instance.Create();
}
}
}