[英]Get data from a file and convert it to dictionary in unity using c#
i am trying to read from a file and convert it into dictionary in unity using c#.The file contains data like 我正在尝试从文件中读取文件,然后使用c#将其统一转换为字典。文件中包含如下数据
1 1 1 acsbd
1 2 1 123ws
here i want to make the first 6 characters to the key and rest characters as values. 在这里我想使键的前6个字符和其余字符作为值。
here is the code i tried(it is mostly from stackoverflow) 这是我尝试过的代码(主要来自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]);
}
It complies but gives IndexOutOfRangeException
exception thrown on run time 它符合但给了运行时抛出的
IndexOutOfRangeException
异常
Thank you. 谢谢。
Try using Linq : 尝试使用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
Edit : No Linq , no File
version: 编辑 :没有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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.