所以我有一个提示,要求用户输入文件的位置。如果文件不存在,我该怎么做才能让用户重新获取文件位置?这是我目前的代码。我有它的原始形式,因为我正在搞乱它。我接近了,但没有雪茄。提前谢谢!
编辑:因此,如果用户键入c:/file.xml并且它应该是c:/file32.xml,它将崩溃。如何让它让用户再试一次?
static void Main(string[] args)
{
//asks user for location of the XML file
Console.WriteLine("Enter location of XML file and XML file name please. Example - c:/xmlfile.xml");
//XML files becomes "xmlfile"
string xmlfile = Console.ReadLine();
//takes xmlfile and runs it through XPATH
string fileName = xmlfile;
XPathDocument doc = new XPathDocument(fileName);
XPathNavigator nav = doc.CreateNavigator();
//Compile a standard XPath expression
//Selects all of the names
XPathExpression expr;
expr = nav.Compile("/zabbix_export/templates/template/items/item/name | /zabbix_export/templates/template/items/item/description");
XPathNodeIterator iterator = nav.Select(expr);
答案 0 :(得分:2)
while (!File.Exists(xmlFile))
{
Console.WriteLine("Please reenter a valid file name:");
xmlfile = Console.ReadLine();
}
答案 1 :(得分:1)
继续检查文件是否存在,直到用户最终将正确的路径放入:)
string xmlFile;
do
{
Console.WriteLine("Enter location of XML file and XML file name please. Example - c:/xmlfile.xml");
xmlFile = Console.ReadLine();
} while (!File.Exists(xmlFile));
答案 2 :(得分:1)
XPathDocument doc = new XPathDocument(fileName);
while (doc == null)
{
// display prompt
// try to retrieve new value for doc
}
XPathNavigator nav = doc.CreateNavigator();
//Compile a standard XPath expression
//Selects all of the names
XPathExpression expr;
expr = nav.Compile("/zabbix_export/templates/template/items/item/name | /zabbix_export/templates/template/items/item/description");
XPathNodeIterator iterator = nav.Select(expr);