2012-03-30 23 views
0
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>"); 
    } 

错误:该进程无法访问文件 'C: file.xml',因为它正被另一个进程使用

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

为什么呢?如何关闭文件?

回答

2

From MSDN

通过该方法(File.Create)创建的FileStream对象具有无的默认文件共享值;在原始文件句柄关闭之前,没有其他进程或代码可以访问创建的文件。

所以解决方法是

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); 
    } 

编辑:改变取出的StreamWriter的创建和使用一个FileStream
不过,我不喜欢这种方式,通过MSDN的建议。
的StreamWriter有一个构造函数,可以得到一个FileStream,但我认为,如果我们使用

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

我们回到锁定问题。不过,我已经测试过,它的工作原理。
可能StreamWriter构造函数对File.Create返回的FileStream做了一些技巧。

+0

错误:不能将类型'System.IO.FileStream'隐式转换为'System.IO.StreamWriter' – user1263390 2012-03-30 20:17:54

1

使用File.CreateStreamWriter,但不能同时

+0

请编写创建一个样品,然后添加到 – user1263390 2012-03-30 20:22:46

+0

@ user1263390'的StreamWriter SW =新的StreamWriter(路径+ “\\ file.xml”,假);' – 2012-03-30 20:28:03

0

sw.Close();你叫Write();

后,您可能会更好使用XmlDocument的。然后你可以附加节点像节点等

XmlDocument有一个内置的保存功能,所以你不必管理任何像一个Streamwriter。

1

变化

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

File.Create(path + "\\file.xml").Close(); 
相关问题