[英]Creating directory if directory exists
I have the following directory: 我有以下目录:
\\\\192.168.255.86\\Add-in\\Requests\\MyFolder1 \\\\ 192.168.255.86 \\外接程序\\ Requests \\ MyFolder1
If this directory exists (there is already a folder on the specified path) I need to create the following: 如果此目录存在(指定的路径上已经有一个文件夹),则需要创建以下内容:
\\\\192.168.255.86\\Add-in\\Requests\\MyFolder1 (1) \\\\ 192.168.255.86 \\ Add-in \\ Requests \\ MyFolder1(1)
If directory still exists I need to create another directory: 如果目录仍然存在,则需要创建另一个目录:
\\\\192.168.255.86\\Add-in\\Requests\\MyFolder1 (2) \\\\ 192.168.255.86 \\ Add-in \\ Requests \\ MyFolder1(2)
and so on. 等等。 I did it using while-loop in the following method:
我是在以下方法中使用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;
}
How to make it using recursion? 如何使用递归?
You don't need recursion here. 您不需要在这里递归。 All you want is create new directory with next available name (by adding number).
您只需要用下一个可用名称(通过添加数字)创建新目录即可。
A slightly refactored method can looks like this: 稍微重构的方法可能如下所示:
public string NextDirectory(string path)
{
var dir = path;
int n = 1;
while (Directory.Exists(dir))
dir = $"{path} ({n++})";
Directory.CreateDirectory(dir);
return dir;
}
If you insist on using recursion, this should be nice and elegant: 如果您坚持使用递归,那么这应该很好:
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)}";
}
But if you already have 'MyFolder1 (214)' your call stack might be immense! 但是,如果您已经拥有“ MyFolder1(214)”,那么您的调用堆栈可能会很大!
Maybe this is a slightly neater way to do the while loop (but essentially the same): 也许这是执行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;
}
You can use this: 您可以使用此:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.