How to modify by loading and saving the same xml file - c#

I have a problem with modifying xml file when i first load and then save it with same file path and name. Below is my code. The error is "Access to the path C:\MyApp\Web.config is denied. If i change the path of the xdoc.Save to be different from xdoc.Load, then it will be ok. What is your recommandation to solve this problem? If possible, i need to modify the existing xml file(meaning xml file for loading and saving is the same path).
XmlDocument xdoc = new XmlDocument();
xdoc.Load(#"C:\\MyApp\\Web.config");
XmlNode xn = xdoc.SelectSingleNode("//configuration/MyProvider");
XmlElement el = (XmlElement)xn;
el.SetAttribute("defaultProvider", "MyCustomValue");
xdoc.Save(#"C:\\MyApp\\Web.config");
Thanks in advance.

I would expect this to be fine if you have write access to web.config to start with, and if nothing else is using it. (It was certainly fine in a test I just ran.) I suspect it's more likely that another process is already using the file (or the same process but some other code within it), or that you simply don't have write access to the file.

Related

Xamarin Android project can't find XML file

I have a file in my Xamarin Android project called "SaveData.xml". I can't save it in the assets folder because I need to write to it during runtime. I am trying to access it with my LoadXML() function:
XmlDocument doc = new XmlDocument();
XmlDocument saveData = new XmlDocument();
public void LoadXML()
{
saveData.Load("SaveData.xml");
//This bit works fine.
AssetManager assets = this.Assets;
using (StreamReader sr = new
StreamReader(assets.Open("Spices.xml")))
{
doc.Load(sr);
}
}
I've tried reading up on it but all the answers say to just save in assets folder. I can't do that because I need to write to this file and then read it again every time the app starts. I also tried putting it in the resources folder and changing the build action. Is the file path wrong? do I need to save it somewhere else? I'm stumped.
EDIT: Sorry for not being specific. "saveData.Load("SaveData.xml")" Is throwing a file not found exception and I want to know why.
Here is the xml file.
SaveData.xml
<?xml version="1.0" encoding="utf-8" ?>
<list>
<cupboard></cupboard>
<shoppingList></shoppingList>
</list>
Yes, if you need to write to the xml during runtime application, we can't put it into the assets folder as it's read-only.
Besides, when you execute saveData.Load("SaveData.xml"), you're not specifying a target directory, so it's defaulting to the root directory, then it will throw a file not found exception.
So you'll need to write the file to a location you have write access to.
The code below will specify a file in the user's home directory, which will be writeable:
using System.IO;
string backingFile_path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "SaveData.xml");
For more details, you can check: https://learn.microsoft.com/en-us/xamarin/android/platform/files/
Note:There is a sample included in this link which you can refer to.

Programmatically Access a File on ASP.NET MVC4

As part of an ASP.NET MVC4 project I need to be able to read from and write to some XML files. I have trouble finding / accessing the files I need.
I've created a demo project to which I've added a folder /Documents containing some XML files.
So in the same project I have a folder /Classes with my class that should read the XML files using XDocument.load().
Here is what I'd like to do (and how I thought it should work):
string path = "/Documents/test.xml"; // Doesn't work
XDocument xml = XDocument.load(path);
However, this doesn't work. Not with "/Documents", "Documents" or "~/Documents".
Supplying the full path works, but not very useful if the website is going to be deployed in other environments.
string path = "D:/Projects/Demo/Demo/Documents/test.xml"; // Works
XDocument xml = XDocument.load(path);
Any suggestions how I can access the files using some kind of relative path?
use Server.MapPath to get the absolute path.
string path = Server.MapPath("/Documents/test.xml");
XDocument xml = XDocument.load(path);
Use HttpContext.Current.Server.MapPath
string path = HttpContext.Current.Server.MapPath("/Documents/test.xml");
Have you tried:
var path = Server.MapPath("/Documents/test.xml");

Parsing XML file using XMLDocument and moving causes exception

I am trying to read an XML file and export the data to DB. I use XMLDocument to read the contents. After exporting the content i am moving the file to a archive location. To avoid name conflicts before moving i am appending the filename with timestamp. The problem is when i repeatedly export the same xml file at one point in time i am getting an exception "The process cannot access the file because it is being used by another program".
My guess is the xml document loaded in memory is not freed yet. Is there any way to avoid this issue?
UPDATE
I tried all the code related to reading and exporting the xml file. My code now has only these lines
fName = DateTime.Now.ToString("yyyyMMddhhmmss") + fileName;
fName = destinationPath + "\\" + fName;
File.Move(sourcePath, fName);
now when i run it first time it works fine. Then i wait for 2 seconds and then try to export it again now it is throwing me an exception
same xml in one point of time cannot be - at least milliseconds must be different. but i think you will get a lot of files. may be you need change the way

Loading FlowDocument.xaml that is part of my solution

I created a FlowDocument.xaml in my current WPF project. What i want to do is when the user clicks a button the XAML document will be loaded in the code behind, have some data on the document modified, and then print it out. The sticking point is i don't know how load the flow document so that i can modify it.
When I do:
FileStream fs = File.Open("FlowDocument.xaml", FileMode.Open)
It says that it can't find the file. The file is part of the project and I'm guessing it gets packaged with the rest of the project when compiled.
Any help is appreciated
Assuming it is configured to be a Resource, then you can load it like so:
FlowDocument doc= Application.LoadComponent(new Uri("/Path/FlowDocument.xaml", UriKind.RelativeOrAbsolute)) as FlowDocument;
This looks like it might be a path/relative path issue...just for testing purposes, try specifying the entire physical/absolute path in the File.Open statement...
You could also do
string path = Directory.GetCurrentDirectory();
to check to see what the current directory is and then make sure that the file FlowDocument.xaml is in that directory

problem while writing data into xml, when event occured

I'm trying to write a little software for logging data, if any type of file created in directory A.
I use FileSystemWatcher class to get information about file creation in folder A. There are many subfolder in folder A. And many users can create file in this directory in one time.
I use XML data to save log data.
XmlTextReader reader = new XmlTextReader(FILE_NAME);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
reader.Close();
XmlNode currNode;
XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
docFrag.InnerXml = "<item>" +
"<path>" + fileName + "</path>" +
"<created>0</created>" +
"<date>" + DateTime.ParseExact(DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss"), "dd.MM.yyyy HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None).ToString() + "</date>" +
"</item>";
// insert the availability node into the document
currNode = doc.DocumentElement;
currNode.InsertAfter(docFrag, currNode.LastChild);
//save the output to a file
doc.Save(FILE_NAME);
But sometimes while occurs watcher.Created += new FileSystemEventHandler(OnChanged);, data about file creation is not inserted to XML file.
So, is it possible if file opened for data writing, and it's locked for new dataWrite file document not saved? and how to fix this.
You are in front of a beauty computer problem, please read a bit about the Dining Philosophers problem in http://en.wikipedia.org/wiki/Dining_philosophers_problem .
You can "lock" a file just setting its attribute to ReadOnly
I mean, when you are going to write, you check if "ReadOnly" is set. In that case
System.IO.File.SetAttributes("pathtofile\filename.ext", FileAttributes.ReadOnly);
After writing, please remove the attribute.
A more complex solution could be the use of semaphores, thus controlling yourself the files that are being accessed. You can find a hint here in StackOverflow:
Problem with using Semaphore to protect queue
Also, you can use this link as a hint to really lock files:
How to lock file
Hope that helps,
Seems that sometimes you open file several times and between this operations file is in different states, so when you write it you just overwrite some data written before. I propose you to collect changes in Queue and write them to the file sequentially.
If you need to log data very often, you should either write to database instead of writing to a file or use buffering.

Categories

Resources