c# - StreamReader 中的子字符串错误

标签 c# substring streamreader unity3d

你好,我在为 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;
}

最佳答案

先读取所有文件数据,再做所有逻辑(Substring等)

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

关于c# - StreamReader 中的子字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36766602/

相关文章:

javascript - 在 JavaScript 中搜索字符串内部

C# 流读取器 ReadToEnd() 缺少最后一个字符

c# - 增加和减少光照强度超时

c# - 无需重新编译项目的本地化

java - C# 中子字符串的实现及其使用的算法是什么?

C++11 正则表达式子串匹配

c# - 需要使用 StreamReader.ReadLine() 获取行终止符

c# - 如何将 Streamreader 数据转换为 XmlDocument?

c# - 如何将日期和时间打包成 32 位?

c# - 如何更改现有命名管道的安全性?