NetworkStream 类、MemoryStream类 和 FileStream 类都提供了以字节为基本单位的读写方法,但是这种方法首先将待写入的数据转换为字节序列后才能进行读写,当操作的是使用字符编码的文本数据时,使用很不方便。因此,在操作文本数据时,一般使用StreamWriter 类与 StreamReader 类执行这些功能。这是因为 Stream 类操作的是字节和字节数组,而 StreamWriter 类与 StreamReader 类自身对底层的转换进行了封装,使开发人员直接操作的就是字符数据,更易于使用。
下面是代码例子:
引入命名空间:
完整代码:
-
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.csdn.net/source/3466066
相关文章:
-
2021-09-30
-
2021-09-21
-
2021-12-10
-
2022-12-23
-
2021-10-30
-
2022-12-23