C#读写txt文件多种方法实例代码
发布时间:2023-08-28 01:20:01
标签:C#,txt文件
1.添加命名空间
System.IO;
System.Text;
2.文件的读取
(1).使用FileStream类进行文件的读取,并将它转换成char数组,然后输出。
byte[] byData = new byte[100];
char[] charData = new char[1000];
public void Read()
{
try
{
FileStream file = new FileStream("E:\\test.txt", FileMode.Open);
file.Seek(0, SeekOrigin.Begin);
file.Read(byData, 0, 100); //byData传进来的字节数组,用以接受FileStream对象中的数据,第2个参数是字节数组中开始写入数据的位置,它通常是0,表示从数组的开端文件中向数组写数据,最后一个参数规定从文件读多少字符.
Decoder d = Encoding.Default.GetDecoder();
d.GetChars(byData, 0, byData.Length, charData, 0);
Console.WriteLine(charData);
file.Close();
}
catch (IOException e)
{
Console.WriteLine(e.ToString());
}
}
(2).使用StreamReader读取文件,然后一行一行的输出。
public void Read(string path)
{
StreamReader sr = new StreamReader(path,Encoding.Default);
String line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line.ToString());
}
}
3.文件的写入
(1).使用FileStream类创建文件,然后将数据写入到文件里。
public void Write()
{
FileStream fs = new FileStream("E:\\ak.txt", FileMode.Create);
//获得字节数组
byte[] data = System.Text.Encoding.Default.GetBytes("Hello World!");
//开始写入
fs.Write(data, 0, data.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();
}
(2).使用FileStream类创建文件,使用StreamWriter类,将数据写入到文件。
public void Write(string path)
{
FileStream fs = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//开始写入
sw.Write("Hello World!!!!");
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
0
投稿
猜你喜欢
- 写在自定义之前我们也许会遇到,自定义控件的触屏事件处理,先来了解一下View类中的,onTouch事件和onTouchEvent事件。1、b
- 前言通过Mybatis做7000+数据量的批量插入的时候报错了,error log如下: , ('G61010352', &
- 功能介绍功能:群聊+私发+上线提醒+下线提醒+查询在线用户文件Utils需要用maven导入下面两个包 <dependency>
- itext生成PDF设置页眉页脚的实例详解实例代码:/** * ITextTest * iText生成PDF加入列表,注释等内容,同时设
- 1.简介if判断语句是很多编程语言的重要组成部分。但是,若我们最终编写了大量嵌套的if语句,这将使得我们的代码更加复杂和难以维护。让我们看看
- 在ajaxcontroltoolkit-a2a6dc6854e0\Client\MicrosoftAjax.Extended\Extende
- 这种属性应用方式是field_name=@field_value@。两个@符号是springboot为替代${}属性占位符产生,原因是${}
- 一、背景项目中新建module之后,要在该目录下新增java Class文件,右键——》New发现无Java Class选项。二、办法Fil
- 一、No serializer found for class org.hibernate.proxy.pojo.bytebuddy.Byt
- 本文实例为大家分享了javafx实现时钟效果的具体代码,供大家参考,具体内容如下核心为三个函数:第一个为 public void dials
- 单个和批量定义别名typeAliases使用Mybatis的别名typeAliases可以在xml文件里非常方便的使用类,而不需要写出这个类
- 拖曳小球WPF的拖曳效果,基本配置一下,就可以了,但是自绘的话,就得自己控制,按键点击,按键移动和按键松开的事件,与其配合达到目的。这个效果
- XmlTextWriter类允许你将XML写到一个文件中去。这个类包含了很多方法和属性,使用这些属性和方法可以使你更容易地处理XML。为了使
- springcloud-gateway集成knife4j环境信息环境信息spring-boot:2.6.3spring-cloud-alib
- 准备数据data class ContactEntity( val letter: Char, &n
- 本文实例讲述了C#实现的XML操作类。分享给大家供大家参考。具体如下:这里讲述了C#写的一个XML操作类,包括读取/插入/修改/删除。usi
- Map简介将键映射到值的对象。一个映射不能包含重复的键;每个键最多只能映射到一个值。此接口取代 Dictionary 类,后者完全是一个抽象
- 目录Profile用法resourcesfilters多环境配置解决方案Profile用法我们在application.yml中为jdbc.
- 现在看我文章的多数是一些老Android了,相信每个人使用起LayoutInflater都是家常便饭,信手拈来。但即使是这样,我仍然觉得这个
- 使用类的全权名: System.Text.StringBuilder sb = new System.Text.StringBuilder(