[英]reading a .txt file and displaying numbers from the file
我正在嘗試使用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
我將其更改為以下內容:
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();
}
}
}
這里有一些注意事項:
您是否考慮row.Length
在訪問row[1]
和row[3]
之前檢查row.Length
我懷疑您的空白行是問題
這是使您更簡單的方法:
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();
}
}
您應該考慮使用:
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();
}
}
問候,
凱文
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.