Writing Text File to Folder on Desktop

房东的猫 提交于 2019-12-24 08:39:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!