c# txt文件的读取和写入

我们在工程实践中经常要处理传感器采集的数据,有时候要把这些数据记录下来,有时候也需要把记录下来的数据读取到项目中。接下来我们用C#演示如何对txt文件进行读写操作。我们要用到StreamReader 和 StreamWriter 类,用于文本文件的数据读写。这些类从抽象基类 Stream 继承,Stream 支持文件流的字节读写。过程如下:

(1)我们新建一个C#控制平台项目,引用System.Io;

(2)定义StreamReader对象,并将要读取文本的路径作为对象的参数;

(3)使用readline方法读取文本中的内容,readline是一行一行的读取。

(4)将读取的内容保存到列表中。

(5)关闭StreamReader对象。

文件的写入和文件的读取类似。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace writehandread
{
    class Program
    {
        static void Main(string[] args)
        {
            //将ys.txt中的内容读取到列表data中
            List<string> data = new List<string>();
            StreamReader sr = new StreamReader("D://test.txt");
            while (sr.ReadLine ()!=null  )
            {              
                data.Add(sr.ReadLine());
                 
            }
            sr.Close();
 
            //将data中的内容写入test.txt中
            StreamWriter sw = new StreamWriter("D://test1.txt");
            for (int i=0 ;i<data .Count ;i++)
            {
                sw.WriteLine(data[i]);
            }
            sw.Flush();
            sw.Close();
 
        }
    }
}
  • 2
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C#中操作XML文件需要使用System.Xml命名空间下的类。 以下是一个简单的示例,演示如何将数据写入XML文件并从中读取数据: ```csharp using System; using System.Xml; class Program { static void Main(string[] args) { // 创建XML文档对象 XmlDocument xmlDoc = new XmlDocument(); // 创建XML声明 XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); // 添加XML声明到XML文档 xmlDoc.AppendChild(xmlDec); // 创建根元素 XmlElement root = xmlDoc.CreateElement("students"); // 将根元素添加到XML文档 xmlDoc.AppendChild(root); // 创建子元素 XmlElement student = xmlDoc.CreateElement("student"); XmlAttribute id = xmlDoc.CreateAttribute("id"); id.Value = "001"; student.Attributes.Append(id); XmlElement name = xmlDoc.CreateElement("name"); name.InnerText = "Tom"; student.AppendChild(name); XmlElement age = xmlDoc.CreateElement("age"); age.InnerText = "18"; student.AppendChild(age); // 将子元素添加到根元素 root.AppendChild(student); // 保存XML文档 xmlDoc.Save("students.xml"); // 读取XML文档 xmlDoc.Load("students.xml"); // 获取根元素 root = xmlDoc.DocumentElement; // 遍历子元素 foreach (XmlElement ele in root.ChildNodes) { Console.WriteLine("Student ID: " + ele.Attributes["id"].Value); Console.WriteLine("Name: " + ele["name"].InnerText); Console.WriteLine("Age: " + ele["age"].InnerText); } Console.ReadLine(); } } ``` 上述代码将创建一个名为“students.xml”的XML文件,其中包含一个名为“students”的根元素和一个名为“student”的子元素。程序会将数据写入文件,然后从文件读取数据并将其打印出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值