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?
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
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
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.