You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

StreamReader读取StreamWriter写入的TXT文件时出现索引越界问题求助

DataGridView读写文本文件索引越界问题的解决方案

嘿,我来帮你搞定这个读取文件时的索引越界问题!先看你给出的写入代码,问题其实出在写入逻辑的细节处理上,导致读取时没法正确解析每行的单元格内容,进而触发索引越界错误。

问题根源分析

  1. 无单元格分隔符:你把每个单元格的内容直接拼接成一行,没有任何分隔标记。读取时如果尝试按列数拆分内容,根本没法区分不同单元格的边界,拆分后的数组长度大概率和DataGridView的列数不匹配,自然会索引越界。
  2. 未跳过新行:DataGridView默认最后一行是空白的「新行」(IsNewRow为true),你写入时也把这行空内容写进了文件,读取时处理这行空内容也会引发错误。

修正后的写入代码

给单元格内容加上分隔符(比如逗号,如果你单元格内容本身有逗号,可以换成|这类不冲突的符号),同时跳过无数据的新行:

StreamWriter sw = new StreamWriter("D:\\test.txt");
string line;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    // 跳过DataGridView默认的空白新行
    if (row.IsNewRow) continue;
    
    line = "";
    foreach(DataGridViewCell cell in row.Cells)
    {
        // 用逗号分隔单元格内容,空值转成空字符串避免空引用
        line += cell.Value?.ToString() + ",";
    }
    // 移除行末尾多余的逗号
    if (!string.IsNullOrEmpty(line))
    {
        line = line.TrimEnd(',');
    }
    sw.WriteLine(line);
}
sw.Close();

配套的读取代码

读取时按分隔符拆分每行内容,同时确保索引不超出DataGridView的列数范围:

StreamReader sr = new StreamReader("D:\\test.txt");
string line;
// 先清空现有行(按需选择,如果你不想保留原有数据的话)
dataGridView1.Rows.Clear();

while ((line = sr.ReadLine()) != null)
{
    // 按写入时的分隔符拆分内容
    string[] cellValues = line.Split(',');
    DataGridViewRow newRow = dataGridView1.Rows.Add();
    
    // 循环赋值时同时判断索引范围,避免越界
    for (int i = 0; i < cellValues.Length && i < dataGridView1.Columns.Count; i++)
    {
        newRow.Cells[i].Value = cellValues[i];
    }
}
sr.Close();

额外注意事项

如果你的单元格内容可能包含分隔符(比如逗号),建议换用更特殊的分隔符(比如|||),或者用引号包裹每个单元格内容,读取时再做对应的解析处理,这样能避免内容拆分错误。

内容的提问来源于stack exchange,提问作者fins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:46:20