Skip to main content
 首页 » 编程设计

c#之创建多个文本文件并写入

2024年02月13日12飞鱼

我想在目标文件夹中创建 100 个文件,下面是源代码,但它会在目标文件夹中创建文件。感谢任何帮助

 class Program 
{ 
      static void Main(string[] args) 
      { 
        int i=1; 
        string path = @"E:\Project\C_Sharp\Tutorial\Console_App\FileSystem\Output\"; 
        if (!File.Exists(path)) 
        { 
            for (i = 1; i < 100; i++) 
            { 
                string FileName = "MyTest" + i + ".txt"; 
                path = FileName; 
                // Create a file to write to.  
                using (StreamWriter sw = File.CreateText(path)) 
                { 
                    sw.WriteLine("Hello"); 
                    sw.WriteLine("And"); 
                    sw.WriteLine("Welcome"); 
                } 
 
            } 
        } 
 
 
 
    } 
} 

请您参考如下方法:

我至少看到 3 处错误。

  1. if (!File.Exists(path)) - path 是一个Directory,而不是一个File.

  2. 如果目录确实存在,您希望进入循环,如果目录不存在则不。否则没有任何意义。

  3. path = Filename; - 您想要将两个字符串连接到一个新变量,而不是覆盖 path。