【问题标题】:Substring error in StreamReaderStreamReader 中的子字符串错误
【发布时间】:2016-04-21 10:17:44
【问题描述】:

您好,我在为 Unity3D 编写编辑器时遇到了问题,我遇到了一个问题,我正在读取具有常规字符串的 .txt 文件中的行,然后是每个常规字符串下方的文件扩展名(代表扩展名的类别)。当我尝试在分配给下一行的字符串上运行子字符串时,问题就出现了。当我尝试使用任何子字符串时,文件显示为打开失败,但没有它,打开就好了。

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;
}

}

【问题讨论】:

  • 欢迎来到 Stack Overflow。你能显示文本文件的例子吗?
  • 你不能只使用 TextAsset 吗?
  • @JoeBlow 我会使用文本资源,但我没有使用 Unity 引擎库,仅使用 Unity 编辑器库

标签: c# unity3d substring streamreader unity5


【解决方案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;
     }

【讨论】:

    【解决方案2】:

    尝试在不打开文件的情况下进行操作:

    StreamReader myStreamReader = new StreamReader(sourceFile.FullName);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多