如何在c#中读取文本文件规范的行和列 [英] how to read text file specifications row and column in c#

查看:47
本文介绍了如何在c#中读取文本文件规范的行和列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取每一行和每一列,但为什么会弹出错误消息确保列表上的最大索引小于列表大小".请帮助...

string[] lines = File.ReadAllLines("C:\\test.txt");for (int i = 0; i 

解决方案

也许你有一个空行或者一行没有 ^.因为您在此处访问字符串数组中的 second 项:

textBox1.Text = line[1];

也许你想总是访问第一个元素,然后使用 0 因为索引是从零开始的:

textBox1.Text = line[0];

然而,更有意义的是

textBox1.Text += line[j];

因为无论如何你都在循环列.

<小时><块引用>

但我只想读取第 1 行和第 1 列......那怎么办??

那么你根本不需要循环:

string firstLinesColumnOne = lines.Length >0 ?行 [0].Split('^')[0] : "";textBox1.Text = firstLinesFirstColumn;

<块引用>

如果我想阅读每一列并显示到不同的文本框?例子文本文件是 row1 {ab cd ef} row2 {dc fc fd} row3 {dg hj ki} 所以输出应该是 textbox1 = 第 1 列 textbox2 = 第 2 列 textbox3 = 第 3 列

假设您想将拆分的三列分配给三个文本框,并为文本框中文件中的每一行添加一个新行:

IEnumerable行列 = 行.Select(line => line.Split('^'));textBox1.Lines = lineColumns.Select(cols => cols[0]).ToArray();textBox2.Lines = lineColumns.Select(cols => cols[1]).ToArray();textBox3.Lines = lineColumns.Select(cols => cols[2]).ToArray();

i want read the each row and column but why it will pop out error message "make sure that the maximum index on a list is less than the list size".pls help...

string[] lines = File.ReadAllLines("C:\\test.txt");

        for (int i = 0; i < lines.Length; i++)
        {
            string[] line = lines[i].Split('^');
            for (int j = 0; j < line.Length; j++)
            {
                textBox1.Text = line[1];

                break;
            }
        }

解决方案

Maybe you have an empty line or a line without ^. Because your accessing the second item in the array of strings here:

textBox1.Text = line[1];

perhaps you want to access always the first element, then use 0 since indices are zero based:

textBox1.Text = line[0];

However, more meaningful would be

textBox1.Text += line[j];

Since you are looping the columns anyway.


but i just want read row 1 and col 1 ...so how ??

Then you don't need a loop at all:

string firstLinesColumnOne = lines.Length > 0 ? lines[0].Split('^')[0] : "";
textBox1.Text = firstLinesFirstColumn;

if i want read each column and display to different text box? example text file is row1 {ab cd ef} row2 {dc fc fd} row3 {dg hj ki} so output should be textbox1 = column 1 textbox2 = column 2 textbox3 = column 3

Assuming you want to assign split three columns to three textboxes and add a new line for every line in the file in the textbox as well:

IEnumerable<String[]> lineColumns = lines
    .Select(line => line.Split('^'));
textBox1.Lines = lineColumns.Select(cols => cols[0]).ToArray();
textBox2.Lines = lineColumns.Select(cols => cols[1]).ToArray();
textBox3.Lines = lineColumns.Select(cols => cols[2]).ToArray();

这篇关于如何在c#中读取文本文件规范的行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆