从不在调试中的文件夹获取txt文件的问题

时间:2019-03-22 20:43:49

标签: c# monogame

我正在和一群同学一起玩Monogame游戏,我们遇到了一个问题。我们正在尝试加载一个.txt文件,该文件位于我们的解决方案文件下面的文件夹中,该文件位于monogame中:

D:\ Profiles \ aa \ Source \ Repos \ s2t3 \ Game \ Game

该文件夹的文件路径本身是: D:\ Profiles \ aa \ Source \ Repos \ s2t3 \ Game \ Game \ AttackPattern \ ratAttackOne.txt

但是,Monogame从以下文件夹开始:

D:\ Profiles \ aa \ Source \ Repos \ s2t3 \ Game \ Game \ bin \ Windows \ x86 \ Debug \

我们如何能够写出要在txt文件中读取的文件名,使其进入游戏,然后进入Attack Pattern?

2 个答案:

答案 0 :(得分:0)

您可以使用Assembly.GetExecutingAssembly来获取调试EXE路径,并通过简单的子字符串搜索将其遍历回bin:

string debugPath = Assembly.GetExecutingAssembly().Location;
string basePath =
    debugPath.Substring(0,debugPath.IndexOf("\\bin\\", StringComparison.InvariantCultureIgnoreCase));
FileInfo fi = new FileInfo(Path.Combine(basePath, "AttackPattern", "ratAttack.txt"));

希望这会有所帮助。我怀疑您知道如何加载文件。

答案 1 :(得分:0)

只需使用StreamReader读取txt文件,即可使用路径... \ Game \ Game \或项目文件夹中的任何内容,而不是调试文件夹中的任何内容。

            try
            {
                //Stream stream = TitleContainer.OpenStream("HighScore.txt");
                StreamReader streamReader = new StreamReader(
                    yourPathToTheTxtFileGoesHere));//for example, \AttackPattern\test.txt

                //do what you want to do with your txt file here

                streamReader.Close();

            }
            catch (FileNotFoundException)
            {

            }