无法进行保存对话框保存文件

时间:2014-11-04 19:45:17

标签: c# visual-studio-2013

所以我试图将随机数列表保存到文本文件中,用户选择随机数量(如果输入数字2,则将2个随机数写入文件)。我已经将数字输出到Visual Studio的默认bin目录中的文本文件中,但是当我尝试允许用户选择保存文件的位置时,即使选择了所需的目录和文件名并单击了保存按钮,该文件未出现在资源管理器中

到目前为止:

 private void writeToFileButton_Click(object sender, EventArgs e)
        {
            //declare streamwriter object
            StreamWriter outputFile;
            outputFile = File.CreateText("Random.txt");

            //declare my counter, random object, and make variable to store user input
            Random rand = new Random();
            int desiredEntries;
            int.TryParse(numberOfEntriesTextbox.Text, out desiredEntries);
            int counter = 1;

            //take user input and generate numbers until user input is equal to counter
            while(counter <= desiredEntries)
            {
                outputFile.WriteLine(rand.Next(100));
                counter++;
            }

            //save resulting file in a txt document
            if (saveRandomFileDialog.ShowDialog() == DialogResult.OK)
            {
                outputFile = File.CreateText(saveRandomFileDialog.FileName);
            }

            else
            {
                MessageBox.Show("you suck");
            }
            outputFile.Close();
        }

1 个答案:

答案 0 :(得分:2)

您正在打开一个文件:

    outputFile = File.CreateText("Random.txt");

写入该文件,然后之后写入文件,然后询问用户他们想要保存文件的位置。我在这看到一个问题。 :)

用以下内容替换上述行:

        outputFile = File.CreateText(saveRandomFileDialog.FileName);

编辑:

基本上,你的代码应该是这样的(我删除了你的部分,但如果你愿意,可以随意侮辱你的用户):)

if (saveRandomFileDialog.ShowDialog() != DialogResult.OK) {
    return;                
}

using (StreamWriter outputFile = File.CreateText(saveRandomFileDialog.FileName)) {

    Random rand = new Random();
    int desiredEntries;
    int.TryParse(numberOfEntriesTextbox.Text, out desiredEntries);
    int counter = 1;

    while (counter <= desiredEntries) {
        outputFile.WriteLine(rand.Next(100));
        counter++;
    }
}