C# 文件加载错误
好吧,我正试图通过C#加载一堆配置文件,当我试图启动程序时,我一直会遇到这个错误C# 文件加载错误,c#,arrays,indexing,user-accounts,C#,Arrays,Indexing,User Accounts,好吧,我正试图通过C#加载一堆配置文件,当我试图启动程序时,我一直会遇到这个错误 C:\C#FILES>program.exe Unhandled Exception: System.IndexOutOfRangeException: Index was outside the boun ds of the array. at ConsoleApplication2.Program.loadAccounts() at ConsoleApplication2.Program.M
C:\C#FILES>program.exe
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the boun
ds of the array.
at ConsoleApplication2.Program.loadAccounts()
at ConsoleApplication2.Program.Main(String[] args)
C:\C#FILES>
我已经调查过了,我认为这与文件中帐户的格式有关
我想知道正确的方法是什么,我已经尝试了我能想到的每一种方法
这是加载帐户的方法
private static void loadAccounts()
{
using (TextReader tr = new StreamReader("accounts.txt"))
{
string line = null;
while ((line = tr.ReadLine()) != null)
{
String[] details = line.Split('\t');
accounts.Add(details[0] + ":" + details[1]);
}
}
}
accounts.txt部分是我不确定的部分,我想应该是这样的
用户名(选项卡)密码
像这样
username password
然而,它给出了上面显示的错误
有人知道正确的帐户格式应该是什么吗?这是因为您从输入中拆分的行不包含请求的元素 由于.NET处理拆分的方式,数组中的第一个(读取:
0
th)元素不太可能是问题的原因
您是否检查过输入文件中是否没有空行?单个空行(甚至在文件末尾)会导致此问题
您可以添加多个检查,例如
if(!string.IsNullOrWhitespace(line)) ...
或
这些是一些检查,或者我建议实施(还有更多需要考虑的),或者两者兼而有之,否则您只是盲目地相信输入值,这通常不是好的做法。您得到了一个IndexOutOfRangeException,这意味着
详细信息
只有一个条目-这意味着该行上没有选项卡
我建议您在拆分之前打印出有问题的行,这样您就可以看到哪一行导致了问题。或者有条件地这样做:
while ((line = tr.ReadLine()) != null)
{
String[] details = line.Split('\t');
if (details.Length == 1)
{
// Or log it, or whatever...
Console.WriteLine("Input error: no tab in line '{0}'", line);
}
else
{
accounts.Add(details[0] + ":" + details[1]);
}
}
我错过了一些东西。。。你在编辑器中检查过这个文件了吗?详细信息[0]或详细信息[1]不存在。数据在读取文件时是否确实以该格式存在?把这行打印出来,这样你就知道是哪一行了,怎么样?
while ((line = tr.ReadLine()) != null)
{
String[] details = line.Split('\t');
if (details.Length == 1)
{
// Or log it, or whatever...
Console.WriteLine("Input error: no tab in line '{0}'", line);
}
else
{
accounts.Add(details[0] + ":" + details[1]);
}
}