2016-04-21 30 views
3

您好我在爲Unity3D編寫編輯器時遇到了麻煩,並且遇到了一個問題,我正在從具有常規字符串的.txt文件讀取行,然後在每個常規字符串下面顯示文件擴展名擴展名類別)。當我嘗試在分配給下一行的字符串上運行子字符串時,問題就出現了。當我嘗試使用任何子字符串時,文件顯示爲打開失敗,但沒有它,打開就好。StreamReader中的子串錯誤

public bool PopulateList() 
{ 
    bool success = true; 
    string path = "Assets/Scripts/Editor/Extensions.txt"; 
    sourceFile = new FileInfo("Assets/Scripts/Editor/Extensions.txt"); 

    if (!File.Exists(path)) 
    { 
     Debug.Log("File Does Not Exist"); 
     TextWriter tw = new StreamWriter(path, true); 
     tw.Close(); 
    } 
    string line; 
    ExtensionUnit anExtension; 

    try 
    { 
     StreamReader myStreamReader = sourceFile.OpenText(); 
     line = myStreamReader.ReadLine(); 

     while (!myStreamReader.EndOfStream) 
     { 
      anExtension = new ExtensionUnit(); 

      anExtension.Categories = line; 
      line = myStreamReader.ReadLine(); 

      /*if(line.Substring(0,1) == ".") 
      { 
       //Debug.Log(line.Substring(0, 1)); 
      }*/ 

      //Debug.Log(line.Substring(0, 1)); 
      /*while(line.Substring(0,1) == ".") 
      { 
       anExtension.Extensions = line; 
       theExtensions.Add(anExtension); 

       //Next extension 
       line = myStreamReader.ReadLine(); 
      }*/ 

      //Empty blank space 
      line = myStreamReader.ReadLine(); 
     } 
     myStreamReader.Close(); 
    } 
    catch 
    { 
     success = false; 
    } 
    return success; 
} 

}

+0

歡迎堆棧溢出。你能展示文本文件的例子嗎? – Vladimir

+0

你不只是簡單地使用TextAsset? – Fattie

+0

@JoeBlow我會使用文本資產,但我沒有使用Unity引擎庫,只使用Unity編輯器庫 –

回答

0

嘗試這樣做,而無需打開文件:

StreamReader myStreamReader = new StreamReader(sourceFile.FullName); 
1

閱讀所有的文件數據,然後再做所有的邏輯(子串等)

public bool PopulateList() 
    { 
     var success = true; 
     var path = "Assets/Scripts/Editor/Extensions.txt"; 

     if (File.Exists(path)) 
      { 
       try 
        { 
        var fileContent = File.ReadAllLines(path); 

        foreach (var line in fileContent) 
         { 
         // Define what lines do you need and get needed extensions 
         } 
        } 

       catch (Exception ex) 
        { 
        Log(ex); // it`s better to know the reason at least 
        success = false; 
        } 
      } 

     return succes; 
    } 
+0

,這個小片段確實幫了我很多,謝謝 –