Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I added a xmlfile in my solution.

I was trying the below program

C#
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.
Posted
Comments
Sergey Alexandrovich Kryukov 21-Oct-14 22:47pm    
Who told you about that '~'?!
—SA

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
 
Share this answer
 
Comments
BillWoodruff 22-Oct-14 0:07am    
The tilde is used in ASP.NET filepath specification, but only for Server Controls:

http://stackoverflow.com/questions/3077558/use-of-tilde-in-asp-net-path
Sergey Alexandrovich Kryukov 22-Oct-14 0:35am    
It's used in Web applications/sites, but I didn't even want to discuss it, because this is totally irrelevant.
It's apparent that it's not applicable to XmlReader.Create("~/ReadingXML/Countries.xml");
—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:
C#
string YourFilePath = @"C:/SomeDirectory/SomeFile.xml";

if(! File.Exists(YourFilePath))
{
     throw new FileNotFoundException("the XML file does not exist");
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900