日期:2014-05-19  浏览次数:21393 次

C#-WinForm 动态创建文本文件(.txt)!
我想在C#中通过一个for循环,生成一个目录,在目录中根据for循环生成单独“.txt”文件,比如:
for(int   i=0;i <6;i++)
{
    //在目录中生成记事本(.txt)文件。
}  
这样我就可以在某个目录中生成六个txt文件了,命名随意,有规律最好!
请问:怎样可以实现上面的功能?谢谢!

------解决方案--------------------
String directory=@ "D:\Test ";
String text;
if(Directory.Exists(directory))
{
}
else
{
Directory.CreateDirectory(directory);
}
for (Int32 i = 0; i < 5; i++)
{
String fileName = directory + "\\ " + i.ToString() + ".txt ";


FileStream fs=File.Create(fileName);


switch (i)
{
case 0:
text = "the first ";
break;
case 1:
text = "the secord ";
break;
case 2:
text = "the three ";
break;
case 3:
text = "the four ";
break;
case 4:
text = "the last ";
break;
default:
text = "the last ";
break;
}
fs.Flush();
fs.Close();
StreamWriter swWriter = new StreamWriter(fileName);
swWriter.WriteLine(text);
swWriter.Flush();
swWriter.Close();