C# winform 创建新文件--写入文本并另存为

使用C#保存文件示例
本文介绍了一个使用C#实现文件保存对话框并写入文本到选定文件的例子。通过SaveFileDialog选择文件路径后,利用StreamWriter将指定文本内容写入到选定的.txt文件中。
ContractedBlock.gifExpandedBlockStart.gifCode
private void button1_Click(object sender, EventArgs e)
        {
            Stream myStream;
            SaveFileDialog saveFileDialog1 
= new SaveFileDialog();

            saveFileDialog1.Filter 
= "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex 
= 1;
            saveFileDialog1.RestoreDirectory 
= true;

            
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                
if ((myStream = saveFileDialog1.OpenFile()) != null)
                {
                    
using (StreamWriter sw = new StreamWriter(myStream))
                    {
                        
// Add some text to the file.
                        sw.Write("This is the ");
                        sw.WriteLine(
"header for the file.");
                        sw.WriteLine(
"-------------------");
                        
// Arbitrary objects can also be written to the file.
                        sw.Write("The date is: ");
                        sw.WriteLine(DateTime.Now);

                    }

                }
            }

        }

转载于:https://www.cnblogs.com/joe-yang/archive/2009/06/18/1506133.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值