c# - 访问在不同项目中但在相同解决方案中的文件
问题描述
我在控制台应用程序项目中创建一个 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
我有两个项目,比如YCMobyDickChallenge
和YCMobyDickWebApp
我试图从 Web 应用程序访问控制台应用程序中的 words.xml 文件。当我调用此操作时,它会给我一个错误。
"System.IO.DirectoryNotFoundException: '找不到路径的一部分'C:\Users\cosku\source\repos\YCMobyDickChallenge\YCMobyDickWebApp\~\YCMobyDickChallenge\YCMobyDickChallenge\bin\Debug\netcoreapp2.1\words.xml' '"
解决方案
既然你已经找到了答案,我会给你一些关于你提供的代码的评论。
- 为什么将文本文件保存在项目文件夹中?如果您经常创建文件,则应考虑在项目文件夹之外创建单独的文件夹。然后将输出文件夹路径保存在一个字符串常量中,并在不同的项目中使用它。您可以拥有一个包含所有您喜欢的常量的类:
public static constant string BatchOutputFolder = @"C:\BatchOutput\";
var xmlPath = Constants.BatchOutputFolder + "words.xml";
- 当您使用“@”符号声明路径字符串时,您不需要双反斜杠“\”。
推荐阅读
- php - 在 DOM 中获取以下节点
- javascript - 双击多选选项编辑
- sql - 将数据从 Dev 复制到 QA 的存储过程
- angular - 我无法在 Angular 中动态更改语言
- sql - 插入后从另一个表中查找最近记录的数据库触发器
- docker-compose - docker-compose deploy 上的 Azure App Service 网络名称不明确错误
- swiftui - 多级导航 SwiftUI
- r - 如何合并 2 列并将它们分开?
- java - 哪个是使用@Singleton EJB 和@Asynchronous 多线程的正确方法?
- python - 为每个组标记数据框中的异常值