This program crashes on debug and highlights the "doc.Save(PATH);" at the end of the code.
I am trying to save the variables cookieScore, additionAddition, and additionMultiplier into an XML file.
I am getting information about it from here "http://visualcsharptutorials.com/net-framework/writing-xml-file"
private XmlDocument doc;
string PATH = #"C:\sample.xml";
private void saveBtn_Click(object sender, EventArgs e)
{
doc = new XmlDocument();
if (!System.IO.File.Exists(PATH))
{
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
XmlComment comment = doc.CreateComment("This is saved game data");
XmlElement root = doc.CreateElement("data");
XmlElement data = doc.CreateElement("data");
XmlAttribute addition = doc.CreateAttribute("addition");
XmlElement additionNumber = doc.CreateElement("additionNumber");
XmlElement multiplicationNumber = doc.CreateElement("multiplicationNumber");
XmlElement cookieSave = doc.CreateElement("cookieSave");
addition.Value = "addition";
additionNumber.InnerText = additionAddition.ToString();
multiplicationNumber.InnerText = additionMultiplier.ToString();
cookieSave.InnerText = cookieScore.ToString();
doc.AppendChild(declaration);
doc.AppendChild(comment);
doc.AppendChild(root);
root.AppendChild(data);
data.Attributes.Append(addition);
data.AppendChild(cookieSave);
data.AppendChild(additionNumber);
data.AppendChild(multiplicationNumber);
doc.Save(PATH);
}
else
{
}
My guess is you're getting an access related exception because you're trying to write to the root of your C drive. Try writing to your desktop instead:
string PATH = #"C:\Users\[yourusername]\Desktop\sample.xml";
Another option would be to try to run your EXE as admin. If it works, then you know that's your problem.
Related
I made game where all of player stats are storage in XML file. When I build a game at mobile device I get an error:
readonly string datapath = #"data.xml";
void CreateNewXMLFile(string name)
{
XmlDocument gamedata = new XmlDocument();
XmlNode docNode = gamedata.CreateXmlDeclaration("1.0", "UTF-8", null);
gamedata.AppendChild(docNode);
//Username
XmlNode GameUsersNode = gamedata.CreateElement("GameUser");
gamedata.AppendChild(GameUsersNode);
//User
XmlNode Username = gamedata.CreateElement("Username");
Username.InnerText = name;
GameUsersNode.AppendChild(Username);
//Lastlogged
XmlNode LastloggedTime = gamedata.CreateElement("LastloggedTime");
LastloggedTime.InnerText = System.DateTime.Now.ToString();
GameUsersNode.AppendChild(LastloggedTime);
//Stage
XmlNode Stage = gamedata.CreateElement("Stage");
Stage.InnerText = "1";
GameUsersNode.AppendChild(Stage);
//Money
XmlNode Money = gamedata.CreateElement("Money");
Money.InnerText = "0";
GameUsersNode.AppendChild(Money);
//GreenHeroLvl
XmlNode GreenHeroLvl = gamedata.CreateElement("GreenHeroLvl");
GreenHeroLvl.InnerText = "0";
GameUsersNode.AppendChild(GreenHeroLvl);
//BlackHero
XmlNode BlackHero = gamedata.CreateElement("BlackHero");
BlackHero.InnerText = "0";
GameUsersNode.AppendChild(BlackHero);
//AssasinHero
XmlNode AssasinHero = gamedata.CreateElement("AssasinHero");
AssasinHero.InnerText = "0";
GameUsersNode.AppendChild(AssasinHero);
gamedata.Save(datapath);
}
Error is:
06-24 21:04:47.092: E/Unity(22918): UnauthorizedAccessException: Access to the path "/data.xml" is denied.
You are trying to write to a system path /data.xml.
On Android you usually don't have permissions to write anything to the root / folder!
I guess you rather want to write e.g. to the Application.persistentDataPath folder like
readonly string datapath = Path.Combine(Application.persistentDataPath, "data.xml");
which on Android results in a valid path like
/storage/emulated/0/Android/data/<packagename>/files/data.xml
I have created an xml file and there are stored my user. The problem, I only ever get the first one out. How do I manage to get all users of the XML file displayed?
private void button1_Click(object sender, EventArgs e)
{
string path = "C:\\temp\\Accounts.xml";
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement root = doc.CreateElement("Login");
XmlElement user = doc.CreateElement("user");
user.InnerText = textBox1.Text;
root.AppendChild(user);
doc.DocumentElement.AppendChild(root);
doc.Save(path);
MessageBox.Show("Created SuccesFully!");
}
private void button2_Click(object sender, EventArgs e)
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("C:\\temp\\Accounts.xml");
foreach (XmlNode person in xdoc.SelectNodes("/Login"))
{
MessageBox.Show(person["user"].InnerText);
}
}
I'm not sure what wasn't working for you, but this works for me. I am using //Login as the path selector. Ensure that your XML file actually has multiple users.
void Main()
{
//Create();
View();
// Output:
// User1
// User2
}
private void Create()
{
string path = "C:\\Code\\Sandbox\\Accounts.xml";
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement root = doc.CreateElement("Login");
XmlElement user = doc.CreateElement("user");
user.InnerText = "User2";
root.AppendChild(user);
doc.DocumentElement.AppendChild(root);
doc.Save(path);
Console.WriteLine("Created SuccesFully!");
}
private void View()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("C:\\Code\\Sandbox\\Accounts.xml");
foreach (XmlNode person in xdoc.SelectNodes("//Login"))
{
Console.WriteLine(person["user"].InnerText);
}
}
Here is the generated XML. I inserted a root Logins element.
<Logins>
<Login>
<user>User1</user>
</Login>
<Login>
<user>User2</user>
</Login>
</Logins>
im almost done with a big project and here's my last error. So I made a XML file where I can add some data, here's the code :
string path = "XMLFile1.xml";
XmlDocument doc = new XmlDocument();
if (!System.IO.File.Exists(path))
{
MessageBox.Show("lmge;lm");
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
XmlComment comment = doc.CreateComment("This is an XML Generated File");
doc.AppendChild(declaration);
doc.AppendChild(comment);
}
else
{
doc.Load(path); MessageBox.Show("Everyting is right?");
}
XmlElement root = doc.DocumentElement;
XmlElement Subroot = doc.CreateElement("Angajat");
XmlElement name = doc.CreateElement("Name");
XmlElement id = doc.CreateElement("ID");
XmlElement password = doc.CreateElement("Password");
XmlElement phone = doc.CreateElement("phone_nr");
XmlElement address = doc.CreateElement("Address");
nume.InnerText = textBox1.Text;
id.InnerText = textBox2.Text;
password.InnerText = textBox3.Text;
phone.InnerText = textBox4.Text;
address.InnerText = textBox5.Text;
Subroot.AppendChild(name);
Subroot.AppendChild(id);
Subroot.AppendChild(password);
Subroot.AppendChild(phone);
Subroot.AppendChild(address);
root.AppendChild(Subroot);
doc.AppendChild(root);
doc.Save(path);
MessageBox.Show("Succes!");
And now I made a login where I get the error
XmlDocument doc = new XmlDocument();
string filename = #"D:\Poriecte Visual\INFO2017\INFO2017\XMLFile1.xml";
doc.Load(filename);
foreach (XmlNode node in doc.SelectNodes("persoane"))
{
String Username = node.SelectSingleNode("ID").InnerText;
String Password = node.SelectSingleNode("Password").InnerText;
if (Username == textBox3.Text && Password == textBox4.Text)
{
Form a = new Form4();
a.Show();
this.Hide();
}
else
{
MessageBox.Show("Something is wrong");
}
And I get this error : enter image description here
My XML file looks like :
<?xml version="1.0" encoding="utf-8"?>
<Persoane>
<Angajat>
<Name>Horatiu Necula</Name>
<ID>horatiu</ID>
<Password>123</Password>
<Phone_nr>0723626741</Phone_nr>
<Address>Valenii de munte ,PH</Address>
</Angajat>
</Persoane>
Help me, I've searched a lot the last few days but nothing worked :\
EDIT: someone helped me and it worked, the path was incorrect , but now I get this error "Object reference not set to an instance of an object" at line 70( string Username = node.SelectSingleNode("ID").InnerText; )
Are you sure the path to your xml file is correct?
This error may occur if the document at the path is actually empty.
Apart from that i would suggest loading the XML file with a FileStream as described here as it gives you a more verbose error set if your file is not available or accesable.
I am trying to update 3 pieces of data in an XML document but getting an "Object Reference Not Set To An Instance Of An Object" error. This is the XML file format I am trying to update:
<?xml version="1.0" encoding="US-ASCII" standalone="true"?>
<ExportSettings xmlns="CompanyName" ExportName="Data Export" Dataset="TestName">
<General>
<AsOfDate>03/31/15</AsOfDate>
<PriceDate>03/31/16</PriceDate>
</General>
<Source>
<Set>Set Name</Set>
</Source>
</ExportSettings>
This is the C# code that is throwing the error:
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
{
string strAsOfDate = dateTimePickerAsOfDate.Text;
string strPriceDate = dateTimePickerPriceDate.Text;
string strSetName = txtboxSet.Text;
XmlDocument doc = new XmlDocument();
doc.Load(strXMLfilepath);
XmlNode General;
XmlNode root = doc.DocumentElement;
General = root.SelectSingleNode("/ExportSettings/General");
General["AsOfDate"].InnerText = strAsOfDate;
General["PriceDate"].InnerText = strPriceDate;
XmlNode Source;
Source = root.SelectSingleNode("/ExportSettings/Source");
Source["Set"].InnerText = strSetName;
doc.Save(strXMLfilepath);
}
}
catch (System.Exception excep)
{
MessageBox.Show(excep.Message);
}
}
Can anyone see the problem? I am not very familiar with updating XML so there may be something basic wrong here.
I've debugged this locally and as Pawel suggests, you need to make some changes regarding namespaces:
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
{
string strAsOfDate = dateTimePickerAsOfDate.Text;
string strPriceDate = dateTimePickerPriceDate.Text;
string strSetName = txtboxSet.Text;
XmlDocument doc = new XmlDocument();
doc.Load(strXMLfilepath);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ab", "CompanyName");
XmlNode General;
XmlNode root = doc.DocumentElement;
General = root.SelectSingleNode("//ab:General", nsmgr);
General["AsOfDate"].InnerText = strAsOfDate;
General["PriceDate"].InnerText = strPriceDate;
doc.Save(strXMLfilepath);
}
}
catch (System.Exception excep)
{
MessageBox.Show(excep.Message);
}
}
Hope this helps.
I created a ping application with a service that pings to URLs. The list of the URLs is stored in an XML file.
My application crashes when I'm trying to add a new site to my XML while the service is running.
VS2010 says my file is being used by some other process but I'm sure that everything is fine. My service isn't using the XML while I'm adding to it.
BUT I guess using an XmlReader & XmlWriter at the same time is where it crashes.
I'll rewrite my code with LINQ to XML but I was wondering if it's possible to use XmlReader & XmlWriter at the same time?
private void saveSites(Site newSite)
{
XmlDocument XDoc = new XmlDocument();
bool fileExists = true;
if (File.Exists("c:\\temp\\sites.xml") == false)
{
createXML();
fileExists = false;
}
using (XmlReader XReader = XmlReader.Create("c:\\temp\\sites.xml"))
{
XDoc.Load(XReader);
if (fileExists == true)
{
XmlNode SiteNode = XDoc.CreateNode(XmlNodeType.Element, "site", "");
XmlNode URLNode = XDoc.CreateNode(XmlNodeType.Element, "url", "");
URLNode.InnerText = newSite.URL;
XmlNode EmailNode = XDoc.CreateNode(XmlNodeType.Element, "email", "");
EmailNode.InnerText = newSite.Email;
SiteNode.AppendChild(URLNode);
SiteNode.AppendChild(EmailNode);
XDoc.DocumentElement.AppendChild(SiteNode);
}
else
{
foreach (Site site in sites)
{
XmlNode SiteNode = XDoc.CreateNode(XmlNodeType.Element, "site", "");
XmlNode URLNode = XDoc.CreateNode(XmlNodeType.Element, "url", "");
URLNode.InnerText= site.URL;
XmlNode EmailNode = XDoc.CreateNode(XmlNodeType.Element, "email", "");
EmailNode.InnerText = site.Email;
SiteNode.AppendChild(URLNode);
SiteNode.AppendChild(EmailNode);
XDoc.DocumentElement.AppendChild(SiteNode);
}
}
XDoc.Save("c:\\temp\\sites.xml");
}
}
Your reader is blocking the writing because it is in the using block. I'd suggest using the Load method the XmlDocument object with a uri instead of creating your own reader. Then also you can separate the initilisation from the writing operation.
Close your XMLReader explicitly.
using (XmlReader reader = XmlReader.Create("file.xml"))
{
while (reader.Read())
{
...
}
reader.Close();
}