2012-03-30 99 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(); 
相關問題