這是我的代碼,它打開一個XML文件(old.xml),過濾無效字符並寫入另一個XML文件(abc.xml)。最後,我將再次加載XML(abc.xml)。當執行followling行時,有異常說xml文件被另一個進程使用,我的代碼在哪裏泄漏?
xDoc.Load("C:\\abc.xml");
有沒有人有什麼想法是什麼錯?我的代碼中有任何泄漏,爲什麼(我一直在使用「使用」關鍵字,感到困惑,看到泄漏......)?
這是我的整個代碼,我在Windows Vista x64下使用C#+ VSTS 2008。
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
Encoding encoding = Encoding.GetEncoding("utf-8", new EncoderReplacementFallback(String.Empty), new DecoderReplacementFallback(String.Empty));
using (TextWriter writer = new StreamWriter(new FileStream("C:\\abc.xml", FileMode.Create), Encoding.UTF8))
{
using (StreamReader sr = new StreamReader(
"C:\\old.xml",
encoding
))
{
int bufferSize = 10 * 1024 * 1024; //could be anything
char[] buffer = new char[bufferSize];
// Read from the file until the end of the file is reached.
int actualsize = sr.Read(buffer, 0, bufferSize);
writer.Write(buffer, 0, actualsize);
while (actualsize > 0)
{
actualsize = sr.Read(buffer, 0, bufferSize);
writer.Write(buffer, 0, actualsize);
}
}
}
try
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load("C:\\abc.xml");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
編輯1:我試圖將緩衝區的大小從10M更改爲1M,它的工作原理!我很困惑,有什麼想法?
編輯2:我發現這個問題很容易重現,當輸入的舊XML文件非常大,像100M或什麼的。我懷疑它是否是.Net已知的錯誤?我將使用ProcessExplorer/ProcessMonitor等工具來查看哪些進程鎖定了文件,以防止它被XmlDocument.Load訪問。
爲什麼這麼大的緩衝區? (儘管它不應該涉及到這個問題,但知道爲什麼10Mb會很有趣)。我可能會使用10K,也許... – 2009-05-18 12:23:01
我試圖將緩衝區的大小從10M更改爲1M,它的工作原理!我很困惑,有什麼想法? – George2 2009-05-18 12:24:47
我在原始代碼中使用大緩衝區大小純粹是爲了測試目的,而不是故意設置的臨時值。 – George2 2009-05-18 12:25:23