【问题标题】:Access a file which is in diffrent project but in same solution访问位于不同项目但在相同解决方案中的文件
【发布时间】:2019-01-05 10:16:31
【问题描述】:

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

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'.'"

【问题讨论】:

  • 我已经解决了它像 string xmlPath=@"~\\YCMobyDickChallenge\\bin\\Debug\\netcoreapp2.1\\words.xml";更改字符串 xmlPath =@"..\\YCMobyDickChallenge\bin\\Debug\\netcoreapp2.1\\words.xml";

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


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多