首页 > 解决方案 > 访问在不同项目中但在相同解决方案中的文件

问题描述

我在控制台应用程序项目中创建一个 xml 文件,然后从 txt 文件中写入数据,并且我在同一个解决方案中有一个 asp.net core mvc 项目。我想在 asp.net core 项目中读取 xml 数据但我无法访问在不同项目中但在相同解决方案中的文件。

public IActionResult List()
    {
        List<Models.Word> wordList = new List<Models.Word>();
  string xmlPath=@"~\\YCMobyDickChallenge\\bin\\Debug\\netcoreapp2.1\\words.xml";
        //using (FileStream fs = new FileStream())
        using (XmlTextReader xmlReader = new XmlTextReader(xmlPath))
        {
            while (xmlReader.Read())
            {
                switch (xmlReader.NodeType)
                {
                    case XmlNodeType.Element:
                        if (xmlReader.Name != "words")
                        {
                            Models.Word word = new Models.Word();
                            word.text = xmlReader.GetAttribute("text");
                  word.count = Convert.ToInt32(xmlReader.GetAttribute("count"));
                            wordList.Add(word);
                        }
                        break;
                }
            }
        }
        wordList.Sort();
        return View(wordList);
    }

在这个名为的解决方案中,YCMobyDickChallenge我有两个项目,比如YCMobyDickChallengeYCMobyDickWebApp我试图从 Web 应用程序访问控制台应用程序中的 words.xml 文件。当我调用此操作时,它会给我一个错误。

"System.IO.DirectoryNotFoundException: '找不到路径的一部分'C:\Users\cosku\source\repos\YCMobyDickChallenge\YCMobyDickWebApp\~\YCMobyDickChallenge\YCMobyDickChallenge\bin\Debug\netcoreapp2.1\words.xml' '"

标签: c#asp.net-core-mvc

解决方案


既然你已经找到了答案,我会给你一些关于你提供的代码的评论。

  1. 为什么将文本文件保存在项目文件夹中?如果您经常创建文件,则应考虑在项目文件夹之外创建单独的文件夹。然后将输出文件夹路径保存在一个字符串常量中,并在不同的项目中使用它。您可以拥有一个包含所有您喜欢的常量的类:

public static constant string BatchOutputFolder = @"C:\BatchOutput\";

var xmlPath = Constants.BatchOutputFolder + "words.xml";
  1. 当您使用“@”符号声明路径字符串时,您不需要双反斜杠“\”。

推荐阅读