DirectoryNotFoundException未处理 [英] DirectoryNotFoundException was unhandled
问题描述
我在我的解决方案中添加了一个xmlfile。
我正在尝试下面的程序
< pre lang =cs> 使用系统;
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Text;
使用 System.Xml;
命名空间 ReadingXML
{
class 程序
{
静态 void Main( string [] args)
{
XmlReader reader = XmlReader.Create( 〜/ ReadingXML / Countries.xml跨度>);
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element)&&(reader.Name == 状态))
{
if (reader.HasAttributes)
{
Console.WriteLine( reader.GetAttribute( name));
}
}
Console.ReadLine();
}
}
}
}
- 我在这里收到错误
XmlReader reader = XmlReader.Create(〜/ ReadingXML / Countries.xml);
- 我试过浏览,但我没有得到确切的答案。
- 如何阅读我在解决方案中添加的xml,以便我可以继续。请帮助。这不是有效的文件名。你不能用〜。如果你删除'〜',它将意味着文件路径从当前卷的根目录开始(无论如何)。此外,没有使用硬编码文件路径的情况。应始终在运行时根据用户输入,一些配置文件和/或环境计算路径名。
有关合法使用应用程序环境的示例,请参阅我过去的回答:
如何找到我的程序目录(可执行目录),
如何查找我的程序目录(当前目录,特殊文件夹)。
一旦摆脱〜并获得正确的文件路径,检查文件是否正确在您尝试阅读它之前存在,并且如果它不存在则执行适当的操作:
string YourFilePath = @ C:/SomeDirectory/SomeFile.xml;
if (!File.Exists(YourFilePath))
{
throw new FileNotFoundException( XML文件不存在);
}
I added a xmlfile in my solution.
I was trying the below program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ReadingXML
{
class Program
{
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create("~/ReadingXML/Countries.xml");
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "State"))
{
if (reader.HasAttributes)
{
Console.WriteLine(reader.GetAttribute("name"));
}
}
Console.ReadLine();
}
}
}
}
--I am getting error here
XmlReader reader = XmlReader.Create("~/ReadingXML/Countries.xml");
--I tried browsing but i didn't get the exact answer.
--How to read the xml which I added in my solution so that I can proceed. Kindly help.
This is not a valid file name. You cannot use "~". If you remove '~', it will mean the file path starting from the root directory on the current volume (bad idea, anyway). Moreover, there are no situations when using hard-coded file paths can be useful. Path names should always be calculated during runtime base on user input, some configuration files and/or environment.
For examples of such legitimate use of the application environment, please see my past answers:
How to find my programs directory (executable directory),
How to find my programs directory (current directory, "special folders").
—SA
Once you get rid of the "~" and get the file path right, check whether the File exists before you try to read it, and do something appropriate if it does not exist:string YourFilePath = @"C:/SomeDirectory/SomeFile.xml"; if(! File.Exists(YourFilePath)) { throw new FileNotFoundException("the XML file does not exist"); }
这篇关于DirectoryNotFoundException未处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!