C#(三十八)之StreamWriter StreamWriter使用方法及与FileStream类的区别

简介: 本篇内容记录了StreamReader类的属性和方法、StreamWriter类的属性和方法等

QQ图片20220426155725.jpg

StreamReader类的属性:


CurrentEncoding:获取流使用的字符编码

EndOfStream:指示当前位置是否在流的末尾

 

StreamReader类的方法:


Read():读取流中的下一个字符或下一组字符。

ReadBlock():读取一个字符块。

ReadLine():从流中读取一行字符

ReadToEnd():从流的当前位置读取到流的末尾

Close():关闭当前流,并释放资源

 

StreamWriter类的属性:


Ecoding:获取被写入类型的字符编码

例:outFile = new StreamWriter ("c://abc.txt",false,Encoding.GetEncoding("gb2312"));

NewLine:当前流使用“行结束符”;

 

StreamWriter类的方法:


Write():写入数据

WriteLine():写入数据,并添加行结束符

Close():关闭当前流,并释放资源

 

StreamXXXX类与FileStream类的区别:


1:StreamReader/StreamWriter操作的是字符数据(char),而FileStream操作的是字节数据(byte):

2:StreamXXXX类常用于文本的打开与保存,而FileStream则用于数据的传输。

3:FileStream是不能指定编码(因为它看到的只是文件的二进制形式,当然无所谓编码),所以如果有中文的文本的话需要转码。

4:FileStream是一个较底层的类,只能简单地读文件到而缓冲区,而StreamXXXX类封装了一些高级的方法,如ReadLine() (按行读取)

5:FileStream类主要使用于大文件读写,StreamXXXXX类主要用于小文件的读写。

 StreamReader


/// <summary>
        /// StreanReader读取
        /// </summary>
        private void button3_Click(object sender, EventArgs e)
        {
            path = textBox1.Text;
            if (path != "" && File.Exists(path))
            {
                try
                {
                    reader = new StreamReader(path, Encoding.Default);
                    string str = reader.ReadToEnd();
                    MessageBox.Show(str);
                }
                catch (Exception qq)
                {
                    MessageBox.Show(qq.Message);
                }
                finally
                {
                    // 关闭文件流
                    reader.Close();
                    // 关闭资源
                    reader.Dispose();
                }
            }
            else
            {
                MessageBox.Show("请输入正确的路径");
                return;
            }
        }

 

StreamWriter


/// <summary>
        /// StreamWrite写入
        /// </summary>
        private void button4_Click(object sender, EventArgs e)
        {
            path = textBox1.Text;
            try
            {
                if (path != "" && File.Exists(path))
                {
                    //创建文件
                    //writer = File.CreateText(path);
                    writer = new StreamWriter(path, false, Encoding.GetEncoding("gb2312"));
                    string contact = @"十年征战梦一场,功名利禄终相忘";
                    writer.Write(contact);
                    MessageBox.Show("写入成功!");
                }
                else
                {
                    MessageBox.Show("请输入正确的路径");
                    return;
                }
            }
            catch (Exception qq)
            {
                MessageBox.Show(qq.Message);
            }
            finally
            {
                writer.Close();
                writer.Dispose();
            }
        }

 

测试使用全部代码:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace FileStreams
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        /// <summary>
        /// 定义一个FileStream类
        /// </summary>
        public FileStream ff = null;
        /// <summary>
        /// 存储文件路径
        /// </summary>
        public string path = "";
        /// <summary>
        /// StreamReader空对象
        /// </summary>
        public StreamReader reader = null;
        /// <summary>
        /// StreamWriter空对象
        /// </summary>
        public StreamWriter writer = null;
        /// <summary>
        /// FileStream读取
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            path = textBox1.Text;
            if (path != "" && File.Exists(path))
            {
                ff = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            }
            else
            {
                MessageBox.Show("请输入正确的路径");
                return;
            }
            try
            {
                byte[] buffer = new byte[1024 * 1024 * 2];    //定义一个2M的字节数组
                //返回本次实际读取到的有效字节数
                int r = ff.Read(buffer, 0, buffer.Length);    //每次读取2M放到字节数组里面
                //将字节数组中每一个元素按照指定的编码格式解码成字符串
                string sss = Encoding.Default.GetString(buffer, 0, r);
                MessageBox.Show(sss);
            }
            catch (Exception qq)
            {
                MessageBox.Show(qq.Message);
            }
            finally
            {
                // 关闭文件流
                ff.Close();
                // 关闭资源
                ff.Dispose();
            }
        }
        /// <summary>
        /// FileStream写入
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
            path = textBox1.Text;
            try
            {
                if (path != "")
                {
                    ff = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    string content = @"大漠孤烟直,长河落日圆";
                    // 将字符串读入字节数组中。
                    byte[] buffer = Encoding.Default.GetBytes(content);
                    // 将数组写入文件
                    ff.Write(buffer, 0, buffer.Length);
                    MessageBox.Show("写入成功");
                }
                else
                {
                    MessageBox.Show("请输入正确的路径");
                    return;
                }
            }
            catch (Exception qq)
            {
                MessageBox.Show(qq.Message);
            }
            finally
            {
                ff.Close();
                ff.Dispose();
            }
        }
        /// <summary>
        /// StreanReader读取
        /// </summary>
        private void button3_Click(object sender, EventArgs e)
        {
            path = textBox1.Text;
            if (path != "" && File.Exists(path))
            {
                try
                {
                    reader = new StreamReader(path, Encoding.Default);
                    string str = reader.ReadToEnd();
                    MessageBox.Show(str);
                }
                catch (Exception qq)
                {
                    MessageBox.Show(qq.Message);
                }
                finally
                {
                    // 关闭文件流
                    reader.Close();
                    // 关闭资源
                    reader.Dispose();
                }
            }
            else
            {
                MessageBox.Show("请输入正确的路径");
                return;
            }
        }
        /// <summary>
        /// StreamWrite写入
        /// </summary>
        private void button4_Click(object sender, EventArgs e)
        {
            path = textBox1.Text;
            try
            {
                if (path != "" && File.Exists(path))
                {
                    //创建文件
                    //writer = File.CreateText(path);
                    writer = new StreamWriter(path, false, Encoding.GetEncoding("gb2312"));
                    string contact = @"十年征战梦一场,功名利禄终相忘";
                    writer.Write(contact);
                    MessageBox.Show("写入成功!");
                }
                else
                {
                    MessageBox.Show("请输入正确的路径");
                    return;
                }
            }
            catch (Exception qq)
            {
                MessageBox.Show(qq.Message);
            }
            finally
            {
                writer.Close();
                writer.Dispose();
            }
        }
    }
}



目录
相关文章
|
1月前
|
存储 C# 索引
C# 一分钟浅谈:数组与集合类的基本操作
【9月更文挑战第1天】本文详细介绍了C#中数组和集合类的基本操作,包括创建、访问、遍历及常见问题的解决方法。数组适用于固定长度的数据存储,而集合类如`List<T>`则提供了动态扩展的能力。文章通过示例代码展示了如何处理索引越界、数组长度不可变及集合容量不足等问题,并提供了解决方案。掌握这些基础知识可使程序更加高效和清晰。
61 2
|
1月前
|
C# 索引
C# 一分钟浅谈:接口与抽象类的区别及使用
【9月更文挑战第2天】本文详细对比了面向对象编程中接口与抽象类的概念及区别。接口定义了行为规范,强制实现类提供具体实现;抽象类则既能定义抽象方法也能提供具体实现。文章通过具体示例介绍了如何使用接口和抽象类,并探讨了其实现方式、继承限制及实例化差异。最后总结了选择接口或抽象类应基于具体设计需求。掌握这两者有助于编写高质量的面向对象程序。
64 5
|
1月前
|
C# 数据安全/隐私保护
C# 一分钟浅谈:类与对象的概念理解
【9月更文挑战第2天】本文从零开始详细介绍了C#中的类与对象概念。类作为一种自定义数据类型,定义了对象的属性和方法;对象则是类的实例,拥有独立的状态。通过具体代码示例,如定义 `Person` 类及其实例化过程,帮助读者更好地理解和应用这两个核心概念。此外,还总结了常见的问题及解决方法,为编写高质量的面向对象程序奠定基础。
16 2
|
2月前
|
C#
C#中的类和继承
C#中的类和继承
36 6
|
2月前
|
C#
C#中的overload,overwrite,override的语义区别
以上概念是面向对象编程中实现多态性和继承的重要基石。理解它们之间的区别对于编写清晰、可维护的代码至关重要。
72 7
|
2月前
|
Java C# 索引
C# 面向对象编程(一)——类
C# 面向对象编程(一)——类
29 0
|
2月前
|
开发框架 .NET 编译器
C# 中的记录(record)类型和类(class)类型对比总结
C# 中的记录(record)类型和类(class)类型对比总结
|
4月前
|
存储 安全 C#
C# 类的深入指南
C# 类的深入指南
|
5月前
|
开发框架 前端开发 .NET
C#编程与Web开发
【4月更文挑战第21天】本文探讨了C#在Web开发中的应用,包括使用ASP.NET框架、MVC模式、Web API和Entity Framework。C#作为.NET框架的主要语言,结合这些工具,能创建动态、高效的Web应用。实际案例涉及企业级应用、电子商务和社交媒体平台。尽管面临竞争和挑战,但C#在Web开发领域的前景将持续拓展。
169 3
|
5月前
|
SQL 开发框架 安全
C#编程与多线程处理
【4月更文挑战第21天】探索C#多线程处理,提升程序性能与响应性。了解C#中的Thread、Task类及Async/Await关键字,掌握线程同步与安全,实践并发计算、网络服务及UI优化。跟随未来发展趋势,利用C#打造高效应用。
181 3