NetworkStream 类、MemoryStream类 和 FileStream 类都提供了以字节为基本单位的读写方法,但是这种方法首先将待写入的数据转换为字节序列后才能进行读写,当操作的是使用字符编码的文本数据时,使用很不方便。因此,在操作文本数据时,一般使用StreamWriter 类与 StreamReader 类执行这些功能。这是因为 Stream 类操作的是字节和字节数组,而 StreamWriter 类与 StreamReader 类自身对底层的转换进行了封装,使开发人员直接操作的就是字符数据,更易于使用。
下面是代码例子:
引入命名空间:
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就可以啦。
下面是我上传的已经成功编译的项目包:http://download.youkuaiyun.com/source/3466066
本文介绍了如何使用StreamWriter类来简化文本文件的写入过程。通过示例代码展示了如何创建StreamWriter实例,并利用其WriteLine方法将包含当前时间的信息写入到指定路径下的文本文件中。
1167

被折叠的 条评论
为什么被折叠?



