C# 使用 StreamWriter 写入数据

C# 使用 StreamWriter 写入数据

NetworkStream 类、MemoryStream类 和 FileStream 类都提供了以字节为基本单位的读写方法,但是这种方法首先将待写入的数据转换为字节序列后才能进行读写,当操作的是使用字符编码的文本数据时,使用很不方便。因此,在操作文本数据时,一般使用StreamWriter 类与 StreamReader 类执行这些功能。这是因为 Stream 类操作的是字节和字节数组,而 StreamWriter 类与 StreamReader 类自身对底层的转换进行了封装,使开发人员直接操作的就是字符数据,更易于使用。

下面是代码例子:

  1. using System.IO;  

完整代码:

namespace StreamWriterApp  {  
    class Program  {  
        static void Main(string[] args)  
        {  
            StreamWriter sw = null;  
            string strPath = "C:\\file1.txt";  
            try  
            {  
                sw = new StreamWriter(strPath);  
                sw.WriteLine("当前时间为:" + DateTime.Now);  
                Console.WriteLine("写文件成功!");  
            }  
            catch (Exception ex)  
            {  
                Console.WriteLine("写文件失败:" + ex.Message);  
            }  
            finally  
            {  
                if (sw != null)  
                    sw.Close();  
            }  
            Console.ReadLine();  
        }  
    }  
}  

运行效果。。。。。直接看C盘file1.txt就可以啦。

原文地址:https://www.cnblogs.com/grj001/p/12223752.html