473,396 Members | 1,875 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

File being used by another process c#

Markus
6,050 Expert 4TB
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]
Expand|Select|Wrap|Line Numbers
  1.         private bool insertName()
  2.         {
  3.             try
  4.             {
  5.                 XmlDocument XmlDoc = new XmlDocument();
  6.                 XmlDoc.Load(XmlFilePath);
  7.                 XmlElement NameElement = XmlDoc.CreateElement("name");
  8.                 XmlText UserName = XmlDoc.CreateTextNode("Jemima");
  9.                 NameElement.AppendChild(UserName);
  10.                 XmlDoc.Save(XmlFilePath); // line 69
  11.  
  12.                 return true;
  13.             }
  14.             catch (Exception Excep)
  15.             {
  16.                 MessageBox.Show(Excep.ToString());
  17.                 return false;
  18.             }
  19.         }
[2]
Expand|Select|Wrap|Line Numbers
  1. 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.
  2.    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
  3.    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)
  4.    at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
  5.    at System.Xml.XmlTextWriter..ctor(String filename, Encoding encoding)
  6.    at System.Xml.XmlDocument.Save(String filename)
  7.    at WindowsFormsApplication1.nameCheck.insertName() in C:\Users\Chris\Documents\Visual Studio 2008\Projects\name\name\name.cs:line 69
Oct 21 '08 #1
8 35821
Plater
7,872 Expert 4TB
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
Oct 21 '08 #2
Markus
6,050 Expert 4TB
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.
Oct 21 '08 #3
Curtis Rutland
3,256 Expert 2GB
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)
Expand|Select|Wrap|Line Numbers
  1. System.IO.FileStream fs = new System.IO.FileStream(@"c:\dev\forum.xml", System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite);
  2. XmlDocument XmlDoc = new XmlDocument();
  3. XmlDoc.Load(fs);
  4. fs.Close();
  5. XmlElement NameElement = XmlDoc.CreateElement("Forum");
  6. XmlDoc.DocumentElement.AppendChild(NameElement);
  7. fs = new System.IO.FileStream(@"c:\dev\forum.xml", System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite);
  8. XmlDoc.Save(fs); // line 69
  9.  
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.
Oct 21 '08 #4
Markus
6,050 Expert 4TB
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
Expand|Select|Wrap|Line Numbers
  1. FileStream fs = new FileStream(@XmlFilePath, FileMode.Open, FileAccess.ReadWrite); // line 64
  2.                 XmlDocument XmlDoc = new XmlDocument();
  3.                 XmlDoc.Load(fs);
  4.                 fs.Close();
  5.                 XmlElement NameElement = XmlDoc.CreateElement("Forum");
  6.                 XmlDoc.DocumentElement.AppendChild(NameElement);
  7.                 fs = new FileStream(@XmlFilePath, FileMode.Open, FileAccess.ReadWrite);
  8.                 XmlDoc.Save(fs);
Oct 21 '08 #5
Plater
7,872 Expert 4TB
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
Oct 21 '08 #6
Curtis Rutland
3,256 Expert 2GB
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.
Oct 21 '08 #7
Markus
6,050 Expert 4TB
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?

Expand|Select|Wrap|Line Numbers
  1. private void nameCheck_Load(object sender, EventArgs e)
  2.         {
  3.             // need to check if the xml file exists
  4.             // if not: create it
  5.             XmlFilePath = Path.GetFullPath("names.xml");
  6.             if(File.Exists(XmlFilePath))
  7.             {
  8.                 MessageBox.Show(XmlFilePath + " exists");
  9.             }
  10.             else
  11.             {
  12.                 MessageBox.Show("names.xml doesn't exist -- creating now -- ");
  13.                 nameInput.Text = Path.GetFullPath("names.xml");
  14.                 XmlTextWriter Writer = new XmlTextWriter(XmlFilePath, System.Text.Encoding.UTF8);
  15.                 Writer.WriteStartDocument();
  16.                 Writer.Formatting = Formatting.Indented;
  17.                 //Writer.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
  18.                 Writer.WriteStartElement("names");
  19.                     Writer.WriteStartElement("name");
  20.                     Writer.WriteValue("Mark");
  21.                     Writer.WriteEndElement();
  22.                 Writer.WriteEndElement();
  23.                 Writer.Close();
  24.             }
  25.  
  26.         }
  27.  
Oct 21 '08 #8
roquen
1
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
Mar 23 '10 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

4
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:...
8
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...
4
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...
13
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...
0
nightangel
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...
6
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...
2
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...
0
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...
3
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...
3
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...
0
BarryA
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
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...
0
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...
0
marktang
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,...
0
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...
0
jinu1996
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...
0
tracyyun
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...
0
agi2029
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,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.