0

所以我有一个提示,要求用户输入文件的位置。如果文件不存在,我该如何做到这一点,程序会重新向用户询问文件位置?这是我当前的代码。我有它的原始形式,因为我在搞乱它。我有点接近,但没有雪茄。提前致谢!

编辑:所以,如果用户输入 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);
4

3 回答 3

2
while (!File.Exists(xmlFile))
{
       Console.WriteLine("Please reenter a valid file name:");
        xmlfile = Console.ReadLine();
}
于 2012-06-22T20:33:31.887 回答
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));
于 2012-06-22T20:31:57.950 回答
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);
于 2012-06-22T20:32:18.027 回答