我有以下目录:
\\ 192.168.255.86 \外接\请求\ MyFolder1
如果此目录存在(指定路径上已有文件夹),我需要创建以下内容:
\\ 192.168.255.86 \ Add-in \ Requests \ MyFolder1(1)
如果目录仍然存在,我需要创建另一个目录:
\\ 192.168.255.86 \ Add-in \ Requests \ MyFolder1(2)
等等。 我使用while循环在以下方法中完成了它:
public static string CreateDirectory(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
return path;
}
int i = 1;
while (Directory.Exists(path + $" ({i})"))
{
i++;
}
path += $" ({i})";
Directory.CreateDirectory(path);
return path;
}
如何使用递归制作它?
答案 0 :(得分:3)
这里你不需要递归。您只需创建具有下一个可用名称的新目录(通过添加数字)。
稍微重构的方法可能如下所示:
public string NextDirectory(string path)
{
var dir = path;
int n = 1;
while (Directory.Exists(dir))
dir = $"{path} ({n++})";
Directory.CreateDirectory(dir);
return dir;
}
答案 1 :(得分:2)
如果你坚持使用递归,这应该是优雅和优雅的:
public static string CreateDirectory(string path, int suffix = 0)
{
string directoryPath = DirectoryPath(path, suffix);
if (!CreateDirectory(directoryPath))
return CreateDirectory(path, i + 1);
return directoryPath;
}
private static bool CreateDirectory(string path)
{
if (Directory.Exists(path))
return false;
Directory.CreateDirectory(path);
return true;
}
private static string DirectoryPath(string path, int suffix)
{
return $"{path}{(suffix > 0 ? $" ({suffix})" : string.Empty)}";
}
但如果你已经拥有'MyFolder1(214)',你的调用堆栈可能会非常大!
也许这是一个稍微简洁的方法来进行while循环(但基本相同):
public static string CreateDirectory(string path)
{
string createPath = GetUniquePath(path);
Directory.CreateDirectory(createPath);
return createPath;
}
private static string GetUniquePath(string path)
{
string result = path;
int i = 1;
while (Directory.Exists(result))
result = $"{path} ({i++})";
return result;
}
答案 2 :(得分:0)
您可以使用:
public static string CreateDirectory(string path, int i)
{
if (i>0)
{
if (Directory.Exists(path + $" ({i})"))
return CreateDirectory(path,++i);
else
{
Directory.CreateDirectory(path + $" ({i})"));
return path + $" ({i})";
}
}
else
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
return path;
}
else
return CreateDirectory(path,1);
}