views:

333

answers:

4

hi

I am creating an xml file. I need to check first if the file exists or not. If the file does not exist, create it and add the data cmg from a .cs file.

If the file exists, don't create the file just add the data cmg from a .cs file.

My code looks like this:

string filename="c:\\employee.xml";
XmlTextWriter tw=new XmlTextWriter(filename,null);//null represents 
the Encoding Type//
tw.Formatting=Formatting.Indented; //for xml tags to be indented//
tw.WriteStartDocument(); //Indicates the starting of document (Required)//
tw.WriteStartElement("Employees"); 
tw.WriteStartElement("Employee","Genius");
tw.WriteStartElement("EmpID","1");
tw.WriteAttributeString("Name","krishnan");
tw.WriteElementString("Designation","Software Developer");
tw.WriteElementString("FullName","krishnan Lakshmipuram Narayanan");
tw.WriteEndElement();
tw.WriteEndElement();
tw.WriteEndDocument(); 
tw.Flush();
tw.Close();
  • so next time we add data to file we need to check if the file exits and add data to xml file
  • and as we have made empID as a primary key, if user tries to make duplicate entry we need to avoid

Is this possible to do?

A: 

Have a look at the File.Exists method here

Blounty
+4  A: 
if (!File.Exists(filename))
{
    // create your file
}

or

if (File.Exists(filename))
{
    File.Delete(filename);
}

// then create your file

File class is in System.IO namespace (add using System.IO; to your file)

marc_s
Do check or at least prepare for File Permission exception if your web app is indeed writing a file at the C: root.
o.k.w
o.k.w - yes, good point!
marc_s
+1  A: 

You can't append records to an XML file, you have to read the file and then rewrite it.

So, just check if the file exists, and read the records from it. Then write the file including all previous records and the new record.

Guffa
A: 

Testing for existance of a file before attempting to create it inherently is subject to a "things change after check" race condition. Who can guarantee you that your application isn't preempted and put to sleep for a moment after you checked, someone else creates/deletes that file, your app gets to run again and does exactly the opposite of what you intended ?

Windows (as well as all UN*X variants) supports file open/create modes that allow to perform that create-if-nonexistant/open-if-existant operation as a single call.

As far as .NET goes, this means for your task (create an XML file) you'd first create a System.IO.FileStream with the appropriate modes, see http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx and then pass that stream to the XmlWriter constructor. That's safer than simply performing an "exists" check and hoping for the best.

FrankH.