I am trying to append to an .xml file using the code[1] below, but I keep coming across the error[2]. Any idea what could be causing it? Thanks.
[1] - private bool insertName()
-
{
-
try
-
{
-
XmlDocument XmlDoc = new XmlDocument();
-
XmlDoc.Load(XmlFilePath);
-
XmlElement NameElement = XmlDoc.CreateElement("name");
-
XmlText UserName = XmlDoc.CreateTextNode("Jemima");
-
NameElement.AppendChild(UserName);
-
XmlDoc.Save(XmlFilePath); // line 69
-
-
return true;
-
}
-
catch (Exception Excep)
-
{
-
MessageBox.Show(Excep.ToString());
-
return false;
-
}
-
}
[2] - System.IO.IOException: The process cannot access the file 'C:\Users\Chris\Documents\Visual Studio 2008\Projects\name\name\bin\Debug\names.xml' because it is being used by another process.
-
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
-
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
-
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
-
at System.Xml.XmlTextWriter..ctor(String filename, Encoding encoding)
-
at System.Xml.XmlDocument.Save(String filename)
-
at WindowsFormsApplication1.nameCheck.insertName() in C:\Users\Chris\Documents\Visual Studio 2008\Projects\name\name\name.cs:line 69
8 35821
Maybe you cannot save() to the same place you load()? (That seems silly to me, but maybe?)
If it bugs you, get a copy of ProcessExplorer from the windows developement section and do a search for the filename, it will list all the processes that have a handle open to that file
Maybe you cannot save() to the same place you load()? (That seems silly to me, but maybe?)
If it bugs you, get a copy of ProcessExplorer from the windows developement section and do a search for the filename, it will list all the processes that have a handle open to that file
Might be silly, but it seems true: I changed the Save() path and it worked, although there was nothing appended to the file. Seems I need help my .xml stuff.
OK, here's something to try.
.Load is overloaded, so instead of providing a filename, provide a FileStream object. Here's the gist (slightly modified to fit my test environment) -
System.IO.FileStream fs = new System.IO.FileStream(@"c:\dev\forum.xml", System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite);
-
XmlDocument XmlDoc = new XmlDocument();
-
XmlDoc.Load(fs);
-
fs.Close();
-
XmlElement NameElement = XmlDoc.CreateElement("Forum");
-
XmlDoc.DocumentElement.AppendChild(NameElement);
-
fs = new System.IO.FileStream(@"c:\dev\forum.xml", System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite);
-
XmlDoc.Save(fs); // line 69
-
Notice how we close the FileStream. That should make sure that the file is available for writing.
Also, notice that in your code you're never modifying the original XmlDocument. In my code, I say XmlDoc.DocumentElement.AppendChild(NameElement) to actually append that name element into the document.
One more suggestion. When you are debugging, comment out your try/catch, so that you not only get the error message, you can get the line number and stack trace.
Thanks, Curt. But now the error has moved to the FileStream fs line.
Error:
sers\Chris\Documents\Visual Studio 2008\Projects\name\name\bin\Debug\names.xml' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
at WindowsFormsApplication1.nameCheck.insertName() in C:\Users\Chris\Documents\Visual Studio 2008\Projects\name\name\name.cs:line 64
-
FileStream fs = new FileStream(@XmlFilePath, FileMode.Open, FileAccess.ReadWrite); // line 64
-
XmlDocument XmlDoc = new XmlDocument();
-
XmlDoc.Load(fs);
-
fs.Close();
-
XmlElement NameElement = XmlDoc.CreateElement("Forum");
-
XmlDoc.DocumentElement.AppendChild(NameElement);
-
fs = new FileStream(@XmlFilePath, FileMode.Open, FileAccess.ReadWrite);
-
XmlDoc.Save(fs);
Is that file used anywhere else?
Such as possibly being constantly updated by some other process?
Is this happening on a webpage? Each webpage will roughly "spawn a thread" so you could get race conditions with threads
Do you have this file open by any other program? Do you have this file open anywhere else in the program that gets called before this method? Because your original code worked for me, actually. You need to find out what is actually locking this file. Because if something in your earlier code is locking it, you would still be able to load from it, all that requires is read access. When you try to gain write access by saving it, it's erroring out.
I don't think that .Load actually locks the file.
Thanks for your patience.
I call this method when the form is loaded, and it works with the xml file (creating it). Could that be the problem? -
private void nameCheck_Load(object sender, EventArgs e)
-
{
-
// need to check if the xml file exists
-
// if not: create it
-
XmlFilePath = Path.GetFullPath("names.xml");
-
if(File.Exists(XmlFilePath))
-
{
-
MessageBox.Show(XmlFilePath + " exists");
-
}
-
else
-
{
-
MessageBox.Show("names.xml doesn't exist -- creating now -- ");
-
nameInput.Text = Path.GetFullPath("names.xml");
-
XmlTextWriter Writer = new XmlTextWriter(XmlFilePath, System.Text.Encoding.UTF8);
-
Writer.WriteStartDocument();
-
Writer.Formatting = Formatting.Indented;
-
//Writer.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
-
Writer.WriteStartElement("names");
-
Writer.WriteStartElement("name");
-
Writer.WriteValue("Mark");
-
Writer.WriteEndElement();
-
Writer.WriteEndElement();
-
Writer.Close();
-
}
-
-
}
-
Hey guys,
I realise that I is kinda late, but still better late than never. I was having simila problem recently. I used XMLWriter to subsequently update xml file and was recieving the same errors. I found the clean solution for this:
The XMLWriter uses underlaying FileStream to access the modified file. Problem is that when you call XMLWriter.close() method, the underlaying stream doesn't get closed and is locking the file. What you need to do is to instantiate your XMLWriter with settings and specify that you need that underlaying stream closed.
example:
XMLWriterSettings settings = new Settings();
settings.CloseOutput = true;
XMLWriter writer = new XMLWriter(filepath, settings);
Hope it helps
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Mountain Bikn' Guy |
last post by:
I am having serious problems with the following IDE bug:
Could not write to output file 'x.dll' -- 'The process cannot access the
file because it is being used by another process. '
and
BUG:...
|
by: Gabe Moothart |
last post by:
Hi,
I'm writing a windows service which interacts with a separate process.
Basically, it calls a process which creates a file, and then my service
reads that file. The problem is, the external...
|
by: funkmusha |
last post by:
I am trying to read a log file using vb.net. I get an error stating
"The process cannot access the file 'C:\test.log' because it is being
used by another process." Below is a sample of what I am...
|
by: George |
last post by:
Hi,
I am re-writing part of my application using C#. This application starts
another process which execute a "legacy" program. This legacy program writes
to a log file and before it ends, it...
|
by: nightangel |
last post by:
Hi dude,what i was done in my application is uploading a image file to my server using FTP, it work great when pushing a file into the server path using FTP.
The problem i met now is i need to do a...
|
by: Studlyami |
last post by:
Is it possible to open a file for reading, while another process has it open for writing to it? One of the problems is that the process that is writing to it is written in C and is running on a...
|
by: Newbie |
last post by:
Hi,
I have a situation where my application is trying to access a file, that
another application may have temporalily open.
The error I get is
The process cannot access the file...
|
by: Tim Golden |
last post by:
aditya shukla wrote:
Why on earth are you *specifying* c:\python25 as the
directory for this file? It's automatically created
in your user-specific temp directory which has specific
permissions...
|
by: =?Utf-8?B?RnJhbmsgVXJheQ==?= |
last post by:
Hi all
I am trying to loop a Textfile.
This Textfile is located on a shared drive and it is
used by another process.
When I try to read it I get an exeption:
The process cannot access the...
|
by: gracepaul |
last post by:
hi,
i got an exception while i m trying to zip/unzip a database inside the serverfolder
System.IO.IOException: The process cannot access the file...
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
| |