Can't load XML from Resource/Drawable/ - c#

I've saved my Xml in Resource/Drawable/ . I put it here cause is the only place where it can stay without any error.
Any way this is the exception:
System.IO.FileNotFoundException: Could not find file "/sds".
How can I find the path?
Here is my code:
String conditionName = "";
XDocument xml = XDocument.Load("#drawable/LightConditions.xml");
foreach (XElement item in xml.Root.Elements("Condizione"))
{
if (item.Element("EV").Value == EV)
{
conditionName = item.Parent.Element("Nome").Value;
break;
}
//do something
}

You will want to place that .xml in the Assets folder and flag the build action as an AndroidAsset.
Then you can use the AssetManager to access it via a Stream:
string conditionName = "";
using (StreamReader sr = new StreamReader(this.Assets.Open("LightConditions.xml")))
{
XDocument xml = XDocument.Load(sr);
foreach (XElement item in xml.Root.Elements("Condizione"))
{
if (condizione.Element("EV").Value == EV)
{
conditionName = item.Parent.Element("Nome").Value;
break;
}
//do something
}
}
Consult the Xamarin.Android guide on Assets

Related

How to create and save an XML file containing complete hierarchy of files and folders for a specified folder?

this is my first post here on the site :)
So basically I need a gui application that can create and save XML file containing complete hierarchy of files and folders for a specified folder.
1.Each folder should be qualified with: Folder name, Folder size (bytes) and Number of files.
2.Each file should be qualified with: File name, File size (bytes), File creation, File last access time, File last modified time.
After the XML file is created the application needs to display the entire folder hierarchy tree (by using the TreeView class).
Can anyone provide help and answer? Thanks!
Try following code. Fully tested. Start with small Directory. Very large folders may take time. I updated code to speed up loading the treeview.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace WindowsFormsApplication29
{
public partial class Form1 : Form
{
XDocument doc = null;
public Form1()
{
InitializeComponent();
folderBrowserDialog1.SelectedPath = #"c:\temp";
}
private void buttonBrowseForFolder_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
textBoxFolderName.Text = folderBrowserDialog1.SelectedPath;
}
private void buttonCreateXml_Click(object sender, EventArgs e)
{
if(Directory.Exists(textBoxFolderName.Text))
{
string header = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><Directory></Directory> ";
doc = XDocument.Parse(header);
XElement root = doc.Root;
CreateXmlRecursive(textBoxFolderName.Text, root);
}
}
private float CreateXmlRecursive(string folder, XElement folderElement)
{
folderElement.SetValue(folder);
DirectoryInfo dInfo = new DirectoryInfo(folder);
int numberOfFiles = 0;
float size = 0.0f;
foreach(FileInfo fInfo in dInfo.GetFiles())
{
try
{
float fSize = fInfo.Length;
size += fSize;
folderElement.Add(new XElement("File", new object[] {
new XAttribute("size",fSize),
new XAttribute("creationDate", fInfo.CreationTime.ToShortDateString()),
new XAttribute("lastAccessDate", fInfo.LastAccessTime.ToShortDateString()),
new XAttribute("lastModifiedDate", fInfo.LastWriteTime.ToShortDateString()),
fInfo.Name
}));
numberOfFiles += 1;
}
catch(Exception e)
{
Console.WriteLine("Error : CAnnot Access File '{0}'", fInfo.Name);
}
}
foreach(string subFolder in Directory.GetDirectories(folder))
{
XElement childDirectory = new XElement("Directory");
folderElement.Add(childDirectory);
float dSize = CreateXmlRecursive(subFolder, childDirectory);
size += dSize;
}
folderElement.Add(new XAttribute[] {
new XAttribute("size", size),
new XAttribute("numberOfFiles", numberOfFiles)
});
return size;
}
private void buttonCreateTree_Click(object sender, EventArgs e)
{
if (doc != null)
{
TreeNode rootNode = new TreeNode(doc.Root.FirstNode.ToString());
AddNode(doc.Root, rootNode);
treeView1.Nodes.Add(rootNode);
treeView1.ExpandAll();
}
}
private void AddNode(XElement xElement, TreeNode inTreeNode)
{
// An element. Display element name + attribute names & values.
foreach (var att in xElement.Attributes())
{
inTreeNode.Text = inTreeNode.Text + " " + att.Name.LocalName + ": " + att.Value;
}
// Add children
foreach (XElement childElement in xElement.Elements())
{
TreeNode tNode = inTreeNode.Nodes[inTreeNode.Nodes.Add(new TreeNode(childElement.Value))];
AddNode(childElement, tNode);
}
}
}
}
Your question is - can u do my application for me - but anyway.
I will give you some hints to get started with your Project.
First of all - Check out MVVM here. This will help you - to handle WPF.
1. Pick the starting folder
Then you will need a FolderPicker to start your Search
public static string PickFolder()
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
string folder = string.Empty;
switch (result)
{
case System.Windows.Forms.DialogResult.OK: return dialog.SelectedPath;
case System.Windows.Forms.DialogResult.Cancel: return string.Empty;
default: return string.Empty;
}
}
U will need the System.Windows.Forms Assembly for this. (Project -> Add reference -> Assembly)
2. folders and files
Then you want to itterate through all folders.
Check out System.IO.Directory here
3. file information
Check out System.IO.File here - this will give you some file data and to get the file size check this out

X document overwriting the existing file in c#

var filename = "C:\\Users\\qadeer.hussain\\Desktop\\gw-msg.log";
var xmlText = new StringBuilder();
bool isXml = false;
foreach (var line in System.IO.File.ReadLines(filename))
{
if (line.Trim().StartsWith("<Message"))
isXml = true;
if (isXml)
{
xmlText.Append(line);
if (line.Trim().EndsWith("</Message>"))
{
//Response.Write(xmlText.ToString());
var xdoc= XDocument.Parse(xmlText.ToString());
xdoc.Save("C:\\Users\\qadeer.hussain\\Desktop\\gw-msg-2.log");
xmlText.Clear();
isXml = false;
}
}
}
i am getting xml data from log file now i have a many xml tag and i am reading that tag when is read a tag i save it into file but the problem is every time my file is overwritten i want my file is not overwritten
using(var writer = File.CreateText(YOUR_FILE_NAME)))
{
....
foreach (var line in System.IO.File.ReadLines(filename))
{
...
//replace xdoc.Save(YOUR_FILE_NAME)
writer.WriteLine(xdoc.ToString());
}
}
By the way. The document you get will not be a valid XML docuemnt. It will be a series of concatinated valid XML documents.

Trying to use a remotely hosted XML file for settings

Apologies for the newbie question, I'm only on day 2 of my adventures with C#...
I'm trying to use a remotely hosted XML file to retrieve some basic settings for my program. I've managed to get it to download and parse the XML file into string variables, but I cannot work out how to make these variables available to the rest of my program.
Here is the code:
public static void getSetting()
{
try
{
XmlDocument xml = new XmlDocument();
xml.Load("http://www.domain.com/s/settings.xml");
XmlNodeList xnList = xml.SelectNodes("/Settings/Setting");
string strEnabled = ""; string strPort = "";
string strPac = ""; string strRules = ""; string strUpdateUrl = "";
foreach (XmlNode xn in xnList)
{
strEnabled = xn["Enabled"].InnerText;
strPort = xn["Port"].InnerText;
strPac = xn["Pac"].InnerText;
strRules = xn["Rules"].InnerText;
strUpdateUrl = xn["UpdateUrl"].InnerText;
}
}
catch (Exception e)
{
Console.WriteLine("Unable to download settings: " + e);
}
}
public static void useSettings()
{
//use the settings in here
}
I'd also appreciate any critique on my code as I'm still getting to grips with everything and realise that I'm probably not going about this the best way.

Read Large XML file using XPath

I am trying to read windows update package.xml file which is roughly 65mb in size, I am trying to just grab the URL attribute using Xpath but for some odd reason my object always returns empty. Here is my code:
doc.Load(#".\package.xml");
string xpath= "/OfflineSyncPackage/FileLocations/FileLocation/#Url";
XmlNodeList nodeList2 = doc.SelectNodes(xpath);
I have also tried using XmlReader which is also not working for me:
string packXML = #".\package.xml";
using (XmlReader xr = XmlReader.Create(packXML))
{
while (xr.Read())
{
switch (xr.NodeType)
{
case XmlNodeType.Element:
if (xr.Name == "OfflineSyncPackage")
{
xr.ReadStartElement("FileLocations");
if (xr.Name == "FileLocations")
{
if (xr.Name == "FileLocation")
{
}
}
}
break;
}
}
}
The package.xml file can be found in package.cab which is in this file: http://download.windowsupdate.com/microsoftupdate/v6/wsusscan/wsusscn2.cab
What is the best way to do this as I do not want to load whole file into memory due to size
Any advice is appreciated! Thank you
I figured this out finally!
public void ParseXML(string XMLPath)
{
XmlReader xmlReader = XmlReader.Create(XMLPath);
while (xmlReader.Read())
{
if (xmlReader.Name.Equals("FileLocation") && (xmlReader.NodeType == XmlNodeType.Element))
{
string url = xmlReader.GetAttribute("Url");
}
}
}

System.IO exception coming while saving XML document in C#

After importing plenty of XML files into application i tried to do modifications on it by using XML document class, for this i created few methods to do modifications.
The thing is the starting method it's working fine and when comes to the second one it's displaying System.IO exception like "File is already using another process".
So any one help me out how can i solve this issue.
Sample code what i'm doing:
Method1(fileList);
Method2(fileList);
Method3(fileList);
private void Method1(IList<RenamedImportedFileInfo> fileList)
{
try
{
string isDefaultAttribute = Resource.Resources.ImportIsDefaultAttribute;
string editorsPath = editorsFolderName + Path.DirectorySeparatorChar + meterType;
string profilesPath = profileFolderName + Path.DirectorySeparatorChar + meterType;
string strUriAttribute = Resource.Resources.ImportUriAttribute;
foreach (RenamedImportedFileInfo renameInfo in fileList)
{
if (renameInfo.NewFilePath.ToString().Contains(editorsPath) && (renameInfo.IsProfileRenamed != true))
{
var xmldoc = new XmlDocument();
xmldoc.Load(renameInfo.NewFilePath);
if (xmldoc.DocumentElement.HasAttribute(isDefaultAttribute))
{
xmldoc.DocumentElement.Attributes[isDefaultAttribute].Value = Resource.Resources.ImportFalse;
}
XmlNodeList profileNodes = xmldoc.DocumentElement.GetElementsByTagName(Resource.Resources.ImportMeasurementProfileElement);
if (profileNodes.Count == 0)
{
profileNodes = xmldoc.DocumentElement.GetElementsByTagName(Resource.Resources.ImportBsMeasurementProfileElement);
}
if (profileNodes.Count > 0)
{
foreach (RenamedImportedFileInfo profileName in oRenamedImportedFileList)
{
if (profileName.NewFilePath.ToString().Contains(profilesPath))
{
if (string.Compare(Path.GetFileName(profileName.OldFilePath), Convert.ToString(profileNodes[0].Attributes[strUriAttribute].Value, CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase) == 0)
{
profileNodes[0].Attributes[strUriAttribute].Value = Path.GetFileName(profileName.NewFilePath);
renameInfo.IsProfileRenamed = true;
break;
}
}
}
}
xmldoc.Save(renameInfo.NewFilePath);
xmldoc = null;
profileNodes = null;
}
}
oRenamedImportedFileList = null;
}
catch (NullReferenceException nullException) { LastErrorMessage = nullException.Message; }
}
Thanks,
Raj
You are probably opening the same file twice in your application. Before you can open it again, you have to close it (or leave it open and work on the same document without opening it again).
For help on how to implement this, please show us more code so we can give you advice.

Categories