user1263390
user1263390

Reputation: 187

The process cannot access the file 'C:\file.xml' because it is being used by another process

 DirectoryInfo dir=new DirectoryInfo(path);
 if (!dir.Exists)
  {
      Directory.CreateDirectory(path);
      File.Create(path + "\\file.xml");

      StreamWriter sw =new StreamWriter(path + "\\file.xml");
      sw.Flush();
      sw.Write("<?xml version='1.0' encoding='utf-8' ?><project></project>");
  }

error:

The process cannot access the file 'C:\file.xml' because it is being used by another process.

why? How can close file?

Upvotes: 0

Views: 10733

Answers (4)

x06265616e
x06265616e

Reputation: 864

Change

File.Create(path + "\\file.xml");

To

File.Create(path + "\\file.xml").Close();

Upvotes: 1

FlavorScape
FlavorScape

Reputation: 14299

Do sw.Close(); after you've called Write();

You may be better off using XmlDocument. Then you can append nodes like nodes etc.

XmlDocument has a built-in Save function so you don't have to manage any of that like a streamwriter.

Upvotes: 0

Steve
Steve

Reputation: 216303

From MSDN

The FileStream object created by this method (File.Create) has a default FileShare value of None; no other process or code can access the created file until the original file handle is closed.

So the workaround is

  using(FileStream fs = File.Create(path + "\\file.xml"))
  {
       Byte[] info = new UTF8Encoding(true).GetBytes("<?xml version='1.0' encoding='utf-8' ?><project></project>");
       fs.Write(info, 0, info.Length);
  }

EDIT: Changed removing the creation of the StreamWriter and using a FileStream
However I don't like this way as suggested by MSDN.
StreamWriter has a constructor that can get a FileStream, but I thought that if we use

   using(StreamWriter sw = new StreamWriter(File.Create(path + "\\file.xml")))
   { 
      sw.Write("<?xml version='1.0' encoding='utf-8' ?><project></project>");
   }

we get back the locking problem. However, I have tested and it works.
Probably the StreamWriter constructor do some tricks on the FileStream returned by File.Create.

Upvotes: 2

L.B
L.B

Reputation: 116138

use File.Create or StreamWriter, not both

Upvotes: 1

Related Questions