【问题标题】:Appending input to file [duplicate]将输入附加到文件[重复]
【发布时间】:2016-05-02 14:55:48
【问题描述】:

我希望程序运行,每次用户点击按钮时,我都想将其添加到文件中,到目前为止,程序一直在用用户输入的新信息覆盖内容。

    private void tradeMethod()
    {
        newTrade.Analysis = textBox1.Text;
        newTrade.Trend = textBox2.Text;
        newTrade.entryLevel = double.Parse(textBox3.Text);
        newTrade.bottomLine = double.Parse(textBox4.Text);
        newTrade.Picture = textBox5.Text;
        newTrade.entrySetup = textBox6.Text;
        string Analysis = newTrade.Analysis;
        string Trend = newTrade.Trend;
        double entryLevel = newTrade.entryLevel;
        double bottomLine = newTrade.bottomLine;
        string Picture = newTrade.Picture;
        string entrySetup = newTrade.entrySetup;


        string[] info = { "The analysis: "+Analysis,"The Trend: " +Trend, "The entry price: " + entryLevel.ToString(), 
                            "The profit/loss of the trade: " + bottomLine.ToString(),"The entry of the trade was: " + entrySetup, "The screnshot of the picture: " +Picture};
        System.IO.File.WriteAllLines(@"C:\\Users\\Samuel\\Documents\\Visual Studio 2013\\Projects\\WindowsFormsApplication8\\WindowsFormsApplication8\\trade.txt", info);
    }

    private void button1_Click(object sender, EventArgs e)
    {

        tradeMethod();

    }

    private void button2_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        try
        {
            StreamReader inputFile;
            string addrLine;

            inputFile = File.OpenText("C:\\Users\\Samuel\\Documents\\Visual Studio 2013\\Projects\\WindowsFormsApplication8\\WindowsFormsApplication8\\trade.txt");
            while (!inputFile.EndOfStream)
            {
                addrLine = inputFile.ReadLine();
                MessageBox.Show(addrLine);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }


}

【问题讨论】:

  • 也许AppendAllLines 可以胜任。
  • 这个基本操作有数百甚至数千个参考。请在提问前做一些基础研究。
  • 我研究了一下,不想加一行。我希望用户每次单击按钮时输入都进入同一个文件。
  • 然后扩展该类型的解决方案以满足您的需求?您不能指望每次研究问题都能找到准确的解决方案。
  • @sam 除了说你做了什么之外,你实际研究了什么......你能告诉我们你做了什么关键词搜索......?也许您在搜索关于将行添加到现有文件的主题时没有使用正确的关键字

标签: c#


【解决方案1】:

Alessandro D'Andria 的评论是正确的。使用方法:

System.IO.File.WriteAllLines

每次都会覆盖文件,删除之前的所有内容。根据System.IO.File 文档,您应该使用:

System.IO.File.AppendAllLines

如果新文件不存在,此方法将处理创建一个新文件。

【讨论】:

    猜你喜欢
    • 2018-08-16
    • 2017-03-08
    • 1970-01-01
    • 2016-03-25
    • 2012-03-07
    • 2012-06-03
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多