我正在尝试使用c#读取.txt文件并显示其内容,但我收到的错误为IndexOutOfRangeException
,错误代码为0xc000013a
。
这是我的代码:
static void Main(string[] args)
{
StreamReader sStreamReader = new StreamReader("d:\\TEST.txt");
while (!sStreamReader.EndOfStream)
{
string sLine = "";
if (sLine != null)
{
sLine = sStreamReader.ReadLine();
if (sLine != null)
{
string[] rows = sLine.Split(",".ToCharArray());
double a = Convert.ToDouble(rows[1]);
Console.Write(a);
int b = Convert.ToInt32(rows[3]);
Console.WriteLine(b);
Console.WriteLine();
}
}
}
}
我的文本文件如下:
1,2,3,4,5,6,7
1,2,3,4,5,6,7
5,6,2,7,3,8,4
3,4,3,4,3
5,3,23,12
12,30000,12,99
答案 0 :(得分:2)
我会将其更改为以下内容:
static void Main(string[] args)
{
// StreamReader is IDisposable which should be wrapped in a using statement
using (StreamReader reader = new StreamReader(@"d:\TEST.txt"))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
// make sure we have something to work with
if (String.IsNullOrEmpty(line)) continue;
string[] cols = line.Split(',');
// make sure we have the minimum number of columns to process
if (cols.Length < 4) continue;
double a = Convert.ToDouble(cols[1]);
Console.Write(a);
int b = Convert.ToInt32(cols[3]);
Console.WriteLine(b);
Console.WriteLine();
}
}
}
这里有一些注意事项:
答案 1 :(得分:1)
您是否考虑在访问row.Length
和row[1]
之前检查row[3]
我怀疑你的空行是问题
答案 2 :(得分:1)
以下是如何做到这一点的简单方法:
string[] lines = File.ReadAllLines("d:\\TEST.txt");
foreach (var line in lines.Where(line => line.Length > 0))
{
string[] numbers = line.Split(',');
// It checks whether numbers.Length is greater than
// 3 because if maximum index used is 3 (numbers[3])
// than the array has to contain at least 4 elements
if (numbers.Length > 3)
{
double a = Convert.ToDouble(numbers[1]);
Console.Write(a);
int b = Convert.ToInt32(numbers[3]);
Console.Write(b);
Console.WriteLine();
}
}
答案 3 :(得分:0)
你应该考虑使用:
if (!string.IsNullOrEmpty(sLine))
而不是
if (sLine != null)
你有这个例外,因为有些行是空的。
但是,这是一种在使用StreamReader时应该编写代码的方法:
using(var reader = new StreamReader(@"d:\\TEST.txt"))
{
string line;
while ((line= reader.ReadLine()) != null)
{
if (string.IsNullOrEmpty(line)) continue;
var rows = line.Split(",".ToCharArray());
var a = Convert.ToDouble(rows[1]);
Console.Write(a);
var b = Convert.ToInt32(rows[3]);
Console.WriteLine(b);
Console.WriteLine();
}
}
此致
凯文