using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Genesis_Solutions_CRMS
{
public partial class formNewAccount : Form
{
public formNewAccount()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Information info = new Information();
info.Name = txtName.Text;
info.Occupation = txtOccupation.Text;
info.Dob = double.Parse(txtDob.Text.ToString());
info.Nic = double.Parse(txtNic.Text.ToString());
info.ID = double.Parse(lblID.Text.ToString());
XMLConfigurarion.XMLConf(info, "DATA.xml");
}
}
}
Dani AI
Generated
The thread is missing two important pieces: the Information class definition and the XMLConfigurarion.XMLConf method. That makes precise advice difficult. The UI code shown parses DOB, NIC and ID as double, which is a common source of bugs: dates belong in DateTime, identifiers are usually int/long (or string if leading zeros are possible), and free-form identity numbers are best kept as string. Use TryParse/TryParseExact so bad input doesn’t throw on save.
A robust, practical workflow that avoids data loss:
- Validate and normalize each field (use
DateTime.TryParseExactfor DOB, numericTryParsefor IDs, trim strings). - Choose a write strategy: LINQ-to-XML (good for manual element/attribute control; see ) or
XmlSerializerwhen theInformationclass maps 1:1 to XML. - Make saves atomic: write to a temporary file and then replace the original. This prevents half-written files on crashes.
- Protect concurrent writers: an
lockfor in-process; a namedMutexfor multi-process apps. - Store the XML in a writable per-user location (ApplicationData) to avoid UAC/permission issues.
Example snippets (validation + atomic save pattern):
DateTime dob;
if (!DateTime.TryParse(txtDob.Text, out dob)) {
// handle invalid date
}
int id;
if (!int.TryParse(lblID.Text, out id)) {
// handle invalid id
} // atomic save: write to temp, then replace or move
string temp = path + ".tmp";
doc.Save(temp);
if (File.Exists(path))
File.Replace(temp, path, null); // preserves backup if needed
else
File.Move(temp, path); Troubleshooting notes: check the exact file path and folder permissions, catch and log IOException/UnauthorizedAccessException during save, and keep a timestamped backup before the first write. For multi-user or high-write scenarios, consider a small DB (SQLite) instead of XML. The earlier posts by , and correctly call for more structure; the missing Information class and XMLConfigurarion method are the key gaps that prevent a tailored sample.
Recommended Answers
Jump to Post— Suzie999 245The question is broad, and with no relevant code to work with.
It is in you best interests to at least show the classes you are working with.
All 4 Replies
Suzie999 245 Coding Hobbyist
The question is broad, and with no relevant code to work with.
It is in you best interests to at least show the classes you are working with.
JOSheaIV 119 C# Addict
I can easily help you with the XML, but I need to know what exactly you want written to the XML, and if you have specific structure in mind.
Details on what needs to be done, and some context would greatly help all of us (just throwing up some code with no backing causes even more questions).
Member #1104501
Hello Ali,
I really like to use the LINQ to XML approach to adding elements and attributes to the XML doc. You'll need to use 'using System.XML.Linq' in order to do this.
Here's an example you can go by:
Let's say I have stored users inside of my xml file. In order to add an entire element to my doc, I will first instantiate my XDocument like so:
private XDocument xDoc = new XDocument();
You will also want the path to your xml file:
private string path = YourXMLPath;
Now you want to load your xml file into xDoc:
xDoc = XDocument.Load(path);
Now you're set to start reading and writing to your xml document. In order to write to your document, it really depends on what your structure is, so here's a sample xml template:
<Table>
<User Name="Name1" Age="20" Gender="Male" Job="Sales" />
</Table>
Here's how you can create a brand new element under Users:
First, I want to put my template inside of an XElement variable:
XElement users = xmlDoc.Element("Table");
The variable addUserToXml will hold my user information from the xml file.
Now let's build a brand new User Element.
var addUser = new XElement("User",
new XAttribute("Name", txtName.Text),
new XAttribute("Age", txtAge.Text),
new XAttribute("Gender", ddlGender.Text),
new XAttribute("Job", txtJob.Text));
Next you want to go ahead and add that User element:
users.Add(new XElement(addUser));
Then save the file:
users.Save(path)
This will add a brand new element under the Table element for a new user every time a user signs up and hits the save button or however you want it setup.
I am going to go ahead and show you a nice elegant way you can read the information from the xml file as well using LINQ to XML. What I will typically do is create a totally new class and create a read function that I can call from anywhere to avoid duplication of code. I will typically have a class called XmlManager that manages all of my xml for me so that I can keep my code nice and clean.
public static DataTable GetUserInformation(){
var datatable = new DataTable();
datatable.Columns.Add("Name");
//Add all columns to DataTable
xmlDoc = XDocument.Load(xmlPath);
var linqQuery = from doc in xmlDoc.Elements("Table").Elements("User")
select new{
Name = doc.Attribute("Name").Value,
Age = doc.Attribute("Age").Value,
Gender = doc.Attribute("Gender").Value,
etc.
}
foreach (var user in linqQuery){
datatable.Rows.Add(user.Name, user.Age, user.Gender, etc.);
}
return datatable;
}
Now you can read that data inside of the datatable. Or you could use a list or whatever you really want to read the data from the datatable. This was a little more info than what you asked for, but if you want to use LINQ to XML, I'd suggest using it with both read and write using XDocument. One other comment, if the file contains sensitive information, make sure that it is encrypted. If it is encrypted, you'll need to decrypt the file or string (depending on how you access the information) before manipulating the data. Hopefully others can benefit from this. I had to struggle through it and look up tons of documentation when I was learning to read and write from and to xml documents.
Here are some nice tutorials that may also help:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=564
Happy Coding!
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.