将文本文件写入桌面上的文件夹

时间:2014-03-05 18:10:21

标签: c# streamwriter

我想知道如何使用StreamWriter将文本文件写入桌面上的特定位置,例如C:\ Users \ tommy \ desktop \ transaction \?

    private void CreateTransaction_Click(object sender, EventArgs e)
    {
        StreamWriter outputFile;
        outputFile = File.CreateText (TID.ToString()+".txt");

        outputFile.WriteLine("Investor :" +" " + InvestorNameLabel.Text);
        outputFile.WriteLine("Initial Amount" + " " +AmountLabel.Text);
        outputFile.WriteLine("Date Invested" +" " +DateLabel.Text);
        outputFile.WriteLine("Period Chosen" + " "+DaysInvestedLabel.Text);
        outputFile.WriteLine("Rate Chosen" + " " + RateLabel.Text);
        outputFile.WriteLine("Total Interest" + " " +InterestAmountLabel.Text);
        outputFile.WriteLine("Transaction Number :" + " " + TransactionIDLabel.Text);
        outputFile.Close();

        MessageBox.Show("Transaction file for Transaction: " + TransactionIDLabel.Text + "Was Created", "Transaction File");


    }

1 个答案:

答案 0 :(得分:16)

如果您知道路径,

       FileStream fs = new FileStream(@"C:\Users\tommy\desktop\transaction\\result.txt",                           FileMode.OpenOrCreate, FileAccess.Write);
       StreamWriter sw = new StreamWriter(fs);
       sw.BaseStream.Seek(0, SeekOrigin.End);
       sw.WriteLine("Investor :" +" " + InvestorNameLabel.Text);
        sw.WriteLine("Initial Amount" + " " +AmountLabel.Text);
        sw.WriteLine("Date Invested" +" " +DateLabel.Text);
        sw.WriteLine("Period Chosen" + " "+DaysInvestedLabel.Text);
        sw.WriteLine("Rate Chosen" + " " + RateLabel.Text);
        sw.WriteLine("Total Interest" + " " +InterestAmountLabel.Text);
        sw.WriteLine("Transaction Number :" + " " + TransactionIDLabel.Text);
        sw.Flush();
        sw.Close();

否则在桌面文件夹中创建一个文件并执行上述操作

使用Environment.SpecialFolder获取桌面路径。

string strPath = Environment.GetFolderPath(
                         System.Environment.SpecialFolder.DesktopDirectory);