问题
I'm wondering how do you write a text file to a specific location on the desktop such as C:\Users\tommy\desktop\transaction\ using StreamWriter?
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:
If you know the path,
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();
else create a file inside the desktop folder and do the above
Use Environment.SpecialFolder to get the path to the desktop.
string strPath = Environment.GetFolderPath(
System.Environment.SpecialFolder.DesktopDirectory);
来源:https://stackoverflow.com/questions/22205767/writing-text-file-to-folder-on-desktop