将数据写入文本文件

时间:2012-12-28 12:33:12

标签: c# file-io console

我有一个简单的程序,我将7个数字中的6个写入文本文件。从逻辑上讲,一切似乎都很好。

但是数字不会按预期写入文件。

Random random = new Random();

Console.WriteLine("Please enter the name of the numbers file");
string fileLotto = Console.ReadLine();
//creating the lotto file
FileStream fs = new FileStream("../../" + fileLotto + ".txt", FileMode.OpenOrCreate, FileAccess.Write);
BufferedStream bs = new BufferedStream(fs);
Console.WriteLine("File created");
fs.Close();
StreamWriter sw = new StreamWriter("../.." + fileLotto + ".txt");

for(int i = 0; i < 6; i++)
{
    for(int j = 0; j < 7; j++)
    {
        //Console.Write(random.Next(1, 49));
        sw.Write(random.Next(1, 49) + " " );

    }
    sw.WriteLine();

}
sw.Close();

文件已创建,但是没有数字写入文件......也许建议为什么?

4 个答案:

答案 0 :(得分:1)

你想做什么?你什么都没说这么多的流?只需使用:

using(StreamWriter sw = new StreamWriter("../.." + fileLotto + ".txt")){
    for(int i = 0; i < 6; i++){
        for(int j = 0; j < 7; j++)
        {
            //Console.Write(random.Next(1, 49));
            sw.Write(random.Next(1, 49) + " " );

    }
    Console.WriteLine();
    }
}

http://msdn.microsoft.com/en-us/library/6ka1wd3w.aspx

答案 1 :(得分:1)

请注意,您的代码未经过优化,并且创建了大量不必要的流和缓冲区,但@Michael的答案概述了在其中使用的正确代码。我的回答只是强调为什么你的代码没有以预期的方式工作。

你的问题的答案实际上很简单。

StreamWriter sw = new StreamWriter("../.." + fileLotto + ".txt");

您忘记将字符串中的/添加到../..。如果假定fileLotto的值为example,则FileStream将创建文件example.txt,但StreamWriter将访问..example.txt进行写入和也是在不同的文件夹中。

使用变量来定义必须重复使用的值。记住DRY原则。

Random random = new Random();

Console.WriteLine("Please enter the name of the numbers file");
string fileLotto = Console.ReadLine();
string fileName = "../../" + fileLotto + ".txt";
//creating the lotto file
FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
Console.WriteLine("File created");
fs.Close();

StreamWriter sw = new StreamWriter(fileName);

for(int i = 0; i < 6; i++)
{
    for(int j = 0; j < 7; j++)
    {
        //Console.Write(random.Next(1, 49));
        sw.Write(random.Next(1, 49) + " " );

    }
    Console.WriteLine();

}
sw.Close();

我再次说请使用@ Michael的代码。这只是为了突出代码的主要问题。

答案 2 :(得分:1)

我必须承认这不是一个奇特的代码。但为什么这不起作用就是这个
在这一行

FileStream fs = new FileStream("../../" + fileLotto + ".txt", FileMode.OpenOrCreate, FileAccess.Write);

您正在"../../"文件夹中打开文件,该文件夹是可执行文件的两个文件夹。
但是在这一行

StreamWriter sw = new StreamWriter("../.." + fileLotto + ".txt");

相同的参数是"../..",这会导致另一个文件在文件名的beginnig中打开可执行文件的父文件夹".."。您已在StreamWriter参数的末尾添加额外的'/',以确保您正在编写使用FileStream创建的第一个文件。

答案 3 :(得分:0)

让我们简化一下:

Random random = new Random();
Console.WriteLine("Please enter the name of the numbers file");
string fileLotto = Console.ReadLine();

StringBuilder text = new StringBuilder();
for(int i = 0; i < 6; i++)
{
    for(int j = 0; j < 7; j++)
    {
        text.Append(random.Next(1, 49) + " " );
    }
    Console.WriteLine();
}

File.WriteAllText(string.Format("../../{0}.txt", fileLotto), text.ToString());

此代码也更安全。你没有打开一堆不必要的流(你没有关闭BTW)。相反,你将所有文本放在一起并一次写下来。