我正在尝试从文件中读取并使用c#将其转换为字典。该文件包含
等数据1 1 1 acsbd
1 2 1 123ws
这里我想将前六个字符设为键,将剩余字符设为值。
这是我尝试的代码(它主要来自stackoverflow)
System.IO.StreamReader file = new System.IO.StreamReader (
@"D:\Programming\Projects\Launch pad\itnol\KeySound");
while ((line = file.ReadLine()) != null)
{
char[] line1 = line.ToCharArray();
if (line1.Length >= 11)
{
line1[5] = ':';
line = line1.ToString();
//Console.WriteLine(line);
}
var items = line.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split(new[] { ':' }));
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (var item in items)
{
Debug.Log(item[0]);
dict.Add(item[0], item[1]);
}
它符合但在运行时抛出IndexOutOfRangeException
异常
谢谢。
答案 0 :(得分:2)
尝试使用 Linq :
using System.IO;
using System.Linq;
...
string fileName = @"D:\Programming\Projects\Launch pad\itnol\KeySound";
...
Dictionary<string, string> dict = File
.ReadLines(fileName)
.Where(line => line.Length >= 11) // If you want to filter out lines
.ToDictionary(line => line.Substring(0, 6), // Key: first 6 characters
line => line.Substring(6)); // Value: rest characters
修改:否 Linq ,没有File
版本:
string fileName = @"D:\Programming\Projects\Launch pad\itnol\KeySound";
...
Dictionary<string, string> dict = new Dictionary<string, string>();
// Do not forget to wrap IDisposable into using
using (System.IO.StreamReader reader = new System.IO.StreamReader(fileName)) {
while (true) {
string line = reader.ReadLine();
if (null == line)
break;
else if (line.Length >= 11)
dict.Add(line.Substring(0, 6), line.Substring(6));
}
}