C# 访问位于不同项目中但位于同一解决方案中的文件
我正在控制台应用程序项目中创建一个xml文件,然后从txt文件将数据写入其中,并且我在同一解决方案中有一个asp.net core mvc项目。我想读取asp.net core项目中的xml数据,但我无法访问不同项目中但在同一解决方案中的文件C# 访问位于不同项目中但位于同一解决方案中的文件,c#,asp.net-core-mvc,C#,Asp.net Core Mvc,我正在控制台应用程序项目中创建一个xml文件,然后从txt文件将数据写入其中,并且我在同一解决方案中有一个asp.net core mvc项目。我想读取asp.net core项目中的xml数据,但我无法访问不同项目中但在同一解决方案中的文件 public IActionResult List() { List<Models.Word> wordList = new List<Models.Word>(); string xmlPath=@"~
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);
}
public IActionResult List()
{
List wordList=新列表();
字符串xmlPath=@“~\\YCMobyDickChallenge\\bin\\Debug\\netcoreapp2.1\\words.xml”;
//使用(FileStream fs=new FileStream())
使用(XmlTextReader xmlReader=新的XmlTextReader(xmlPath))
{
while(xmlReader.Read())
{
开关(xmlReader.NodeType)
{
case XmlNodeType.Element:
if(xmlReader.Name!=“words”)
{
Models.Word=newmodels.Word();
word.text=xmlReader.GetAttribute(“文本”);
word.count=Convert.ToInt32(xmlReader.GetAttribute(“count”);
添加(word);
}
打破
}
}
}
Sort();
返回视图(单词列表);
}
在这个名为likeYCMobyDickChallenge
的解决方案中,我有两个项目,如YCMobyDickChallenge
和ycmobydickkwebapp
,我试图从web应用程序访问console应用程序中的words.xml文件。当我调用此操作时,它会给我一个错误,如
System.IO.DirectoryNotFoundException:'找不到
路径
“C:\Users\cosku\source\repos\YCMobyDickChallenge\ycmobydickkwebapp\~\YCMobyDickChallenge\YCMobyDickChallenge\bin\Debug\netcoreapp2.1\words.xml”。”
既然您已经找到了答案,我将对您提供的代码给出一些评论
public静态常量字符串BatchOutputFolder=@“C:\BatchOutput\”代码>
使用“@”符号声明路径字符串时,不需要双反斜杠“\”李>
我像字符串xmlPath=@“~\\YCMobyDickChallenge\\bin\\Debug\\netcoreapp2.1\\words.xml”一样解决了这个问题;更改字符串xmlPath=@“.\\YCMobyDickChallenge\bin\\Debug\\netcoreapp2.1\\words.xml”;
var xmlPath = Constants.BatchOutputFolder + "words.xml";