C# 使用c从文件中获取数据并将其转换为unity中的字典#

C# 使用c从文件中获取数据并将其转换为unity中的字典#,c#,dictionary,unity3d,C#,Dictionary,Unity3d,我试图从一个文件中读取数据,并使用c#将其转换为unity中的字典 1 1 1 acsbd 1 2 1 123ws 在这里,我想将键的前6个字符和其余字符作为值 这是我试过的代码(主要来自stackoverflow) System.IO.StreamReader文件=新建System.IO.StreamReader( @“D:\Programming\Projects\Launch pad\itnol\KeySound”); 而((line=file.ReadLine())!=null)

我试图从一个文件中读取数据,并使用c#将其转换为unity中的字典

1 1 1 acsbd 
1 2 1 123ws 
在这里,我想将键的前6个字符和其余字符作为值

这是我试过的代码(主要来自stackoverflow)

System.IO.StreamReader文件=新建System.IO.StreamReader(
@“D:\Programming\Projects\Launch pad\itnol\KeySound”);
而((line=file.ReadLine())!=null)
{
char[]line1=line.ToCharArray();
如果(line1.Length>=11)
{
第1行[5]=':';
line=line1.ToString();
//控制台写入线(行);
}
var items=line.Split(新[]{'(',')},StringSplitOptions.RemoveEmptyEntries)
.Select(s=>s.Split(new[]{':'}));
Dictionary dict=新字典();
foreach(项目中的var项目)
{
Debug.Log(项[0]);
添加(第[0]项、第[1]项);
}
它符合要求,但在运行时引发了
IndexOutOfRangeException
异常

谢谢。

尝试使用Linq:


好的。那就去做。问题是什么?我想知道怎么做?你尝试了什么?你被困在哪里了?你读了吗?我编辑了这个问题,谢谢你的帮助。现在不要这样做,但它看起来很好,很简单谢谢你的帮助,但是visual studio说
System.IO.File不包含读线的定义
@rishabh kunda:
ReadLines
(请注意最后一个
s
)@DmitryBychenko抱歉,我的评论中有一个打字错误,在代码的
阅读行中,它仍然给出相同的结果error@rishabh昆达:好的,让我们实现无Linq、无
文件
版本(参见我的编辑)。不需要使用
数组
拆分
,而是
子字符串
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]);
         }
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
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));
  }
}