Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中创建文件夹时添加数字后缀#_C#_Directory_Counter - Fatal编程技术网

C# 在C中创建文件夹时添加数字后缀#

C# 在C中创建文件夹时添加数字后缀#,c#,directory,counter,C#,Directory,Counter,我正在尝试处理我要创建的文件夹是否已存在。。要在文件夹名称中添加数字。。像windows资源管理器。。e、 g(新文件夹、新文件夹1、新文件夹2..) 我怎样才能递归地做呢 我知道这个密码是错的。 我如何修复或更改下面的代码来解决问题 int i = 0; private void NewFolder(string path) { string name = "\\New Folder"; if (Directory.Exists(path

我正在尝试处理我要创建的文件夹是否已存在。。要在文件夹名称中添加数字。。像windows资源管理器。。e、 g(新文件夹、新文件夹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 = 0;
  while (Directory.Exists(Path.Combine(path, current)) {
    i++;
    current = String.Format("{0} {1}", name, i);
  }
  Directory.CreateDirectory(Path.Combine(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();
        }
    }
}

非常感谢:)。。嗯,我有个小问题。。我用treeview制作了一个文件浏览器。。现在我想用listview来做。。如何获取ParentNode。。在listview中。。我指的是当前文件夹。。listviewitem中是否有选项,或者我必须将当前路径保存在字符串中?
listviewitem
对象有一个
标记
属性,您可以在其中存储任意数据。你可以把这条路放在这里。。因为某种原因我不知道为什么。。当我给出路径@“d:”。。它是在磁盘c上创建的:。。为什么???@MurHafSoz这是一个非常恼人的Windows遗留问题。如果您不指定至少一个反斜杠,它将为您提供您不期望的行为。因此,
d:`不同于
d:`对不起,我的英语不好。。。我不明白你的意思,我该怎么走?
public static class DirectoryInfoExtender
{
    public static void CreateDirectory(this DirectoryInfo instance)
    {
        if (instance.Parent != null)
        {
            CreateDirectory(instance.Parent);
        }
        if (!instance.Exists)
        {
            instance.Create();
        }
    }
}