469,366 Members | 2,198 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,366 developers. It's quick & easy.

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 35182
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

Post your reply

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

Similar topics

8 posts views Thread by Gabe Moothart | last post: by
3 posts views Thread by =?Utf-8?B?RnJhbmsgVXJheQ==?= | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.