StreamWriter 入门case

本文详细介绍使用C#进行文件读写的步骤与方法,通过具体案例演示如何利用StreamWriter类向文本文件中写入字符串,包括路径设置、写入操作、缓存刷新及流关闭等关键环节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • C#对于文件读写的封装其实做的是很好的,如果想要写字符串,这里简单提供一个case。

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace IO
    {
        /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
    
            private void StreamWriter_Click(object sender, RoutedEventArgs e)
            {
                string path = @"C:\\Users\\15475\\Desktop\\fileInfo\\test.txt";  //Input file path,注意这里要用双斜杠
    
                //创建StreamWriter 类的实例
                StreamWriter streamWriter = new StreamWriter(path);  //可以指定打开的方式,这里默认创建,注意路径写上后缀
    
                //向文件中写入姓名
                streamWriter.WriteLine("yang");  //WriteLine会自动换行,如果write的话需要手动添加换行\r\n
    
                //向文件中写入QQ号
                streamWriter.WriteLine("102365447898");
    
                //刷新缓存
                streamWriter.Flush(); //调用Flush和Close之前文件里面是看不到东西
    
                //关闭流
                streamWriter.Close();
    
                //因为有时不确定close方法是否隐式调用了Dispose所以最好还是养成
                streamWriter.Dispose();
    
            }
        }
    }
    

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值