在多个文件夹中创建文件

时间:2016-05-03 04:45:33

标签: c#

我创建了一个创建 n 文件夹的for循环。我想在每个文件夹中创建一个文本文件。我该怎么做?

for (int i = 1; i < 17; i++)
{                       
    System.IO.Directory.CreateDirectory(
        String.Format(@"C:\Users\xxx\Desktop\xx\Test{0:d2}", i));
}

我找到了更好的解决方案。

for (int i = 1; i < 17; i++)
        {

            Directory.CreateDirectory(String.Format(@"C:\Users\xxx\Desktop\xx\Test"+i, i));                

            if (!File.Exists(string.Format(@"C:\Users\xxx\Desktop\xx\Test{0}/Test.txt", i)))
            {                    
                File.WriteAllText(string.Format(@"C:\Users\xxx\Desktop\xx\Test{0}/Test.txt", i), " ");
            }

4 个答案:

答案 0 :(得分:0)

试试这个

for (int i = 1; i < 17; i++)
{                       
    var folder = System.IO.Directory.CreateDirectory(String.Format(@"C:\Users\xxx\Desktop\xx\Test{0:d2}", i));
    System.IO.File.WriteAllText(folder.FullName + @"\WriteText.txt", "your text content");
}

<强>更新

如果您想要多个文件

 for (int i = 1; i < 17; i++)
 {                       
    var folder = System.IO.Directory.CreateDirectory(String.Format(@"C:\Users\xxx\Desktop\xx\Test{0:d2}", i));
    System.IO.File.WriteAllText(folder.FullName + @"\WriteText1.txt", "your text content 1");
    System.IO.File.WriteAllText(folder.FullName + @"\WriteText2.txt", "your text content 2");
 }

答案 1 :(得分:0)

试试这个:

var desktop_path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
for (int i = 1; i < 17; i++)
{
    var folder_path = System.IO.Path.Combine(desktop_path, String.Format(@"xx\Test{0:d2}", i));
    var file_path = System.IO.Path.Combine(folder_path, "file.txt");
    System.IO.Directory.CreateDirectory(folder_path);
    System.IO.File.WriteAllText(file_path, "content");
}

此代码查找当前用户的桌面路径,然后使用System.IO.Path.Combine确保路径正确连接在一起。

答案 2 :(得分:-1)

  for (int i = 1; i < 17; i++)
    {                       
      var dir = System.IO.Directory.CreateDirectory
      (String.Format(@"C:\Users\xxx\Desktop\xx\Test{0:d2}", i));
      System.IO.File.Create(dir.FullName+ @"\MyFile.txt");
    }

要在文件上创建添加内容,我们可以使用 File.Create()

返回的 FileStream 对象

答案 3 :(得分:-3)

试试上面这个,

我希望这对你来说很容易

 string path = @"d:\\dummyfolder";
        for (int i = 0; i < 17; i++)
        {
            string _folderPath = string.Format("{0}\\{1}", path, i);                
            if (!Directory.Exists(_folderPath))
            {
                //creating folder
                Directory.CreateDirectory(_folderPath);

                //creating text file
                string _filePath = string.Format("{0}\\{1}\\{1}.txt", path, i);                    
                string text = i + " " + "Content of the text file ";
                File.WriteAllText(_filePath, text);

            }
        }