C# 读取文本文件

1.准备工作

  • 引入命名空间System.IO,因为这里面包含了我们要调用的读取文件的类StreamReader

2.举例

(1)待读取文件格式
在这里插入图片描述
(2)思路

  • 实例化一个SteamReader,用完后最后记得关闭它
  • 创建四个一维数组用来存放数据
  • 使用SteamReader.ReadLine函数逐行读取数据
  • 使用Split函数将其分割,将分割后的数组逐个对应存入刚才创建数组的中。
  • 打印验证

(3)代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;    //包含允许读写文件和数据流的类型以及提供基本文件和目录支持的类型。

namespace CA_ReadText
{
    class Program
    {
        static void Main(string[] args)
        {
            ReadFile();
            Console.ReadKey();
        }

        static void ReadFile()
        {
            string fileName = @"D:\C#保存位置\Winforms\KaoyanReview\CA_ReadText\bin\Debug\data.txt";

            var reader = new StreamReader(fileName);

            string buf = reader.ReadLine(); //读取第一行,不需要,所以直接扔掉

            //存储数据
            int[] num = new int[4];
            string[] siteName = new string[4];
            double[] B = new double[4];
            double[] L = new double[4];

            //逐行读取并存储到数组中
            for (int i = 0; i < 4; i++)
            {
                buf = reader.ReadLine();
                var arrLine = buf.Split(' ');
                num[i] = int.Parse(arrLine[0]);
                siteName[i] = arrLine[1];
                B[i] = Convert.ToDouble(arrLine[2]);    //Method 1
                L[i] = double.Parse(arrLine[3]);    //Method 2

                Console.WriteLine("{0},{1},{2},{3}", num[i], siteName[i], B[i], L[i]);//写出
            }

            reader.Close();
        }
    }
}

3.进阶

我不知道大家有没有发现上面的情况的不足之处,接下来我将自己觉得不足的地方跟大家分享并进行改正。

(1)问题

  • 逐行读取写死了,也就是如果不是四行而是更多行,我们岂不是读不到4行之后的内容了
  • 与上个问题对应的就是存储数据那四个数组的格式和大小写死了。

(2)我的思路
针对问题一,我们就使用另外一种循环使得它能够自动识别并读取到最后一行内容为止。针对问题二,我们可以创建一个结构体,使用List来存储,List可以动态的添加后删除数据。
(3)上代码

  • 结构体
struct LineStruct
    {
        public int num;
        public string siteName;
        public double B;
        public double L;
    }
  • 读取函数
static void ReadFilePro()
        {
            string fileName = @"D:\C#保存位置\Winforms\KaoyanReview\CA_ReadText\bin\Debug\data.txt";
            List<LineStruct> list = new List<LineStruct>();
            var reader = new StreamReader(fileName);
            string buf = reader.ReadLine();//第一行舍弃

            while (!reader.EndOfStream)//读取到最后
            {
                buf = reader.ReadLine();
                var line = buf.Split(' ');

                var lineStruct = new LineStruct();
                for (int i = 0; i < line.Length; i++)
                {
                    switch (i)
                    {
                        case 0:
                            lineStruct.num = int.Parse(line[i]);
                            break;
                        case 1:
                            lineStruct.siteName = line[i];
                            break;
                        case 2:
                            lineStruct.B = double.Parse(line[i]);
                            break;
                        case 3:
                            lineStruct.L = double.Parse(line[i]);
                            break;
                    }
                }
                list.Add(lineStruct);
            }
            
            foreach (var item in list)
            {
                Console.WriteLine("{0} {1} {2} {3}", item.num, item.siteName,item.B,item.L);
            }
            reader.Close();
        }

总结

当然了,我写的仍然有很多不足之处,还望各位多加指正。

  • 5
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在C#读取文本文件的行数,可以使用以下代码: ```csharp using System; using System.IO; class Program { static void Main(string\[\] args) { string filePath = "L:\\Code\\1.txt"; // 文件路径 int lineCount = GetLineCount(filePath); // 调用方法获取行数 Console.WriteLine("该文件一共有" + lineCount + "行"); Console.ReadKey(); } public static int GetLineCount(string filePath) { int lineCount = 0; using (StreamReader sr = new StreamReader(filePath)) { while (sr.ReadLine() != null) { lineCount++; } } return lineCount; } } ``` 以上代码中,`GetLineCount`方法接收一个文件路径作为参数,使用`StreamReader`读取文件的每一行,并通过计数器统计行数。最后返回行数。在`Main`方法中,我们调用`GetLineCount`方法并输出行数。请注意,你需要将文件路径`filePath`替换为你实际的文件路径。\[1\] #### 引用[.reference_title] - *1* [C#读取txt文本内容行数](https://blog.csdn.net/qq_22889875/article/details/77924840)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [C#语言读取txt行列数据](https://blog.csdn.net/chengoes/article/details/121409682)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [通过程序 VB.Net 或 C# 读取文本文件行数](https://blog.csdn.net/weixin_34218890/article/details/86309622)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值