Failing to write an XML file on WinXp - c#

i've a problem in my program: running Win XP, it is impossible to write an XML file inside the backgroundworker's doWork();
here is the code inside the BW:
try
{
updateUI(file.FullName, 2);
writeToXml(file, e.Argument.ToString());
}
the creation of xml file:
XDocument xmlDocVideoList = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("..."),
new XElement(/*ns+*/"VideoList"));
xmlDocVideoList.Save(saveFileDialog1.FileName);
the writeToXml method:
public void writeToXml(FileInfo file, string path)
{
fileCounterMapped++;
Video temp = new Video();
temp.nameFile = file.Name;
temp.nameVideo = temp.processNameFile(temp.nameFile);
temp.path = file.Directory.FullName;
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNode node = doc.CreateNode(XmlNodeType.Element, "Video", null);
XmlNode subnodeFN = doc.CreateNode(XmlNodeType.Element, "FileName", null);
XmlNode subnodeVN = doc.CreateNode(XmlNodeType.Element, "VideoName", null);
XmlNode subnodePATH = doc.CreateNode(XmlNodeType.Element, "Path", null);
subnodeFN.InnerText = temp.nameFile;
subnodeVN.InnerText = temp.nameVideo;
subnodePATH.InnerText = temp.path;
node.AppendChild(subnodeFN);
node.AppendChild(subnodeVN);
node.AppendChild(subnodePATH);
doc.DocumentElement.AppendChild(node);
doc.Save(path);
}
In my computer, running Win7 this WORKS, but in all the PC with WinXP doesn't work.
In all computer I use VisualStudio 10 Express and I have the FrameWork 4.
Thanks in advance!

The XDocument Object Belongs to newer versions of .Net maybe try using only the XMLDocument instead.
If you're using .NET version 3.0 or lower, you have to use XmlDocument aka the classic DOM API ... maybe xp isnt supporting this or maybe you need to update your windows.

Related

Cannot fix Improper Restriction of XML External Entity Reference error

I have changed the code when trying to fix Veracode error for Improper Restriction of XML External Entity Reference, but it did not fix it.
Here is the code I have now:
XmlDocument xmlDoc=new XmlDocument();
using (System.IO.MemoryStream xmlstream = new System.IO.MemoryStream
(Encoding.Default.GetBytes(dsEQ.GetXml().ToString())))
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
using (XmlReader xmlreader = XmlReader.Create(xmlstream, settings))
{
try
{
xmlDoc.Load(xmlreader);
}
catch(XmlException e)
{
Connection.LogError(e.ToString(), e.Message);
}
}
}
However, Veracode still point out on this section of code with the same error message.
Is there anything else that I should do to fix it? We do not have any external references, everything is through intranet.
Set XmlResolver to null:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.XmlResolver = null;
Set XmlResolver = null will fix the issue.
static void LoadXML()
{
string xml = "<?xml version=\"1.0\" ?><!DOCTYPE doc
[<!ENTITY win SYSTEM \"file:///C:/Users/user/Documents/testdata2.txt\">]
><doc>&win;</doc>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.XmlResolver = null; // Setting this to NULL disables DTDs - Its NOT null by default.
xmlDoc.LoadXml(xml);
Console.WriteLine(xmlDoc.InnerText);
Console.ReadLine();
}
Please go through below link for more information.
XML External Entity (XXE) Prevention Cheat Sheet
The original answer works for xmlDoc.Load(xmlreader).
The second question is a different context and requires different technology.
using (System.IO.StringReader rxml = new System.IO.StringReader(myxmltext))
{
XmlSerializer serializer = new XmlSerializer(typeof(MenuConfigBase));
using (XmlTextReader xr = new XmlTextReader(rxml))
{
xr.XmlResolver = null;
var cfgBase = (MenuConfigBase)serializer.Deserialize(xr);
}
}

Windows phone 8.1 XDocument xml serialization C#

I'm creating a Windows Phone 8.1 app, and I need to serialize my data to XML.
I have two functions; the first one is creating a document where I can later put my retrieved data.
public async Task make()
{
using (var questions = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(
"data.xml",
CreationCollisionOption.OpenIfExists))
{
XDocument xml = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Root")
);
xml.Save(questions);
}
}
The second one is making serialization to my xml file:
public async Task serial(Tsk tak)
{
using (var questions = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(
"data.xml",
CreationCollisionOption.OpenIfExists))
{
XDocument xml = XDocument.Load(questions);
xml.Root.Add(new XAttribute("Date", tak.Date),
new XElement("time", tak.Time),
new XElement("text", tak.Text)
);
xml.Save(questions);
}
}
The first xml function is making this code:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root />
When I'm running the second function I've got this error: root element is missing. Can anyone tell me how I can get this serialization to work?
Try this, you might need to doctor it a bit:
1) create the document
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("root");
doc.AppendChild(root);
file = await ApplicationData.Current.LocalFolder.CreateFileAsync("data.xml");
await FileIO.WriteTextAsync(file, doc.GetXml());
Debug.WriteLine("Done creating file.");
2) write the new data to the document
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("data.xml");
XDocument doc = XDocument.Load(file.Path);
XElement newQuestion = new XElement("Question",
new XElement("time", tak.Time),
new XElement("text", tak.Text)
).SetAttributeValue("Date", tak.Date);
doc.Root.Add(newQuestion);
await FileIO.WriteTextAsync(file, doc.Root.ToString());

Parsing Amazon s3 bucket listing with C# XmlDocument (Unity3d)

Disclaimer: This issue is happening within a Unity application, but AFAIK, this is more of a C# issue than a Unity issue...
I am trying to use System.Xml.XmlDocument to parse an Amazon S3 bucket listing. Here is my bucket xml. I am using an example that I found in a C# Xml tutorial.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("http://rss.cnn.com/rss/edition_world.rss");
XmlNode titleNode = xmlDoc.SelectSingleNode("//rss/channel/title");
if(titleNode != null)
Debug.Log(titleNode.InnerText);
This works fine for that particular XML file, but when I put my stuff in there:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("https://s3.amazonaws.com/themall/");
Debug.Log ( xmlDoc.InnerXml );
XmlNode nameNode = xmlDoc.SelectSingleNode("//Name");
if(nameNode != null)
Debug.Log(nameNode.InnerText);
I get the raw XML in the console, so I know it is being downloaded successfully, but even the simplest XPath produces no results!
My only theory is that perhaps it has something to do with the default namespace in my XML? Do I need to tell XmlDocument about that somehow? Here is my root tag:
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
I have tried creating an XmlNamespaceManager and using it with all of my calls to "SelectSingleNode", but that doesn't seem to work either.
XPathNavigator nav = xmlDoc.CreateNavigator();
XmlNamespaceManager ns = new XmlNamespaceManager(nav.NameTable);
ns.AddNamespace(System.String.Empty, "http://s3.amazonaws.com/doc/2006-03-01/");
What am I doing wrong?
Thanks!
When you add the namespace to the namespace manager you need to give it a non-empty prefix. According to MSDN:
If the XmlNamespaceManager will be used for resolving namespaces in an XML Path Language (XPath) expression, a prefix must be specified.
Blockquote
The prefix must then be used in your XPath select statement. Here is the code I used and the output was "themall" as expected:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("http://s3.amazonaws.com/themall/");
XmlNamespaceManager namespaceManager =
new XmlNamespaceManager(xmlDoc.NameTable);
namespaceManager.AddNamespace("ns",
"http://s3.amazonaws.com/doc/2006-03-01/");
XmlNode titleNode =
xmlDoc.SelectSingleNode("//ns:Name", namespaceManager);
if (titleNode != null)
Console.WriteLine(titleNode.InnerText);

Windows 8 xml file writing

I have a problem with writing to xml file, placed in my application folder( windows 8, metro style). I’m getting Unauthorized AccessException when I’m trying to open file in read/write mode. I’ve done a lot of research, but still nothing. I tried this solution:
var sf = await Package.Current.InstalledLocation.GetFileAsync(#"data.xml");
XmlDocument xmlDoc;
using (var stream = await sf.OpenAsync(FileAccessMode.ReadWrite))
{
xmlDoc = await XmlDocument.LoadFromFileAsync(sf);
XmlElement root = xmlDoc.DocumentElement;
XmlElement xe = xmlDoc.CreateElement("debt");
XmlElement id = xmlDoc.CreateElement("Id");
id.InnerText = Guid.NewGuid().ToString();
XmlElement name = xmlDoc.CreateElement("Name");
name.InnerText = d.Name;
XmlElement surname = xmlDoc.CreateElement("Surname");
surname.InnerText = d.Surname;
xe.AppendChild(id);
xe.AppendChild(name);
xe.AppendChild(surname);
root.AppendChild(xe);
}
if (xmlDoc != null)
await xmlDoc.SaveToFileAsync(sf);
But again exception occur in line where I'm opening stream.
thx for your help
Package.Current.InstalledLocation.GetFileAsync represents where you application is installed which is an area you cannot directly write files to. Use the following
Windows.ApplicationModel.Package.Current.InstalledLocation
or
Windows.Storage.ApplicationData.Current.LocalFolder.Path
I am using the former and it works fine, see http://metrorssreader.codeplex.com/SourceControl/changeset/view/18082#263004

Reading a *.CSPROJ file in C#

I am attempting to write some code to read in a *.CSPROJ file using C#
The code I have is as follows
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(fullPathName);
XmlNamespaceManager mgr = new XmlNamespaceManager(xmldoc.NameTable);
//mgr.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/2003");
foreach (XmlNode item in xmldoc.SelectNodes("//EmbeddedResource") )
{
string test = item.InnerText.ToString();
}
using the debugger I can see that 'fullPathName" has the correct value and the xmldoc once loaded has the correct contents.
The xmldoc does not have any "Nodes" though, as if the contents are not recognised as XML.
Using a XML editor the *.csproj file validates an XML document.
Where am I going wrong?
Why not use the MSBuild API?
Project project = new Project();
project.Load(fullPathName);
var embeddedResources =
from grp in project.ItemGroups.Cast<BuildItemGroup>()
from item in grp.Cast<BuildItem>()
where item.Name == "EmbeddedResource"
select item;
foreach(BuildItem item in embeddedResources)
{
Console.WriteLine(item.Include); // prints the name of the resource file
}
You need to reference the Microsoft.Build.Engine assembly
You were getting close with your XmlNamespaceManager addition, but weren't using it in the SelectNodes method:
XmlNamespaceManager mgr = new XmlNamespaceManager(xmldoc.NameTable);
mgr.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/2003");
foreach (XmlNode item in xmldoc.SelectNodes("//x:ProjectGuid", mgr))
{
string test = item.InnerText.ToString();
}
(I switched to searching for a different element as my project didn't have any embedded resources)
For completeness here the XDocument version, this simplifies namespace management:
XDocument xmldoc = XDocument.Load(fullPathName);
XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
foreach (var resource in xmldoc.Descendants(msbuild + "EmbeddedResource"))
{
string includePath = resource.Attribute("Include").Value;
}

Categories

Resources