2010-11-21 7 views
1

私のC#アプリケーションからxmlファイルを作成しました。作成後にファイルを使用したいのですが、ファイルがすでに使用中であるという例外が表示されますか?私はここのソースコードがある..私はファイルか何かをクローズする必要があると思う:C#でxmlを再利用する

private void button1_Click(object sender, EventArgs e) 
{ 
    // Create the XmlDocument. 
    XmlDocument doc = new XmlDocument(); 
    doc.LoadXml("<item><name>salman</name></item>"); //Your string here 

    // Save the document to a file and auto-indent the output. 
    XmlTextWriter writer = new XmlTextWriter(@"D:\data.xml", null); 
    writer.Formatting = Formatting.Indented; 
    doc.Save(writer); 
    /////////////// 

    XmlDataDocument xmlDatadoc = new XmlDataDocument(); 
    xmlDatadoc.DataSet.ReadXml(@"D:\data.xml");// here is the exception!!!!! 

    //now reading the created file and display it in grid view 

    DataSet ds = new DataSet("Books DataSet"); 
    ds = xmlDatadoc.DataSet; 
    dataGridView1.DataSource = ds.DefaultViewManager; 
    dataGridView1.DataMember = "CP"; 

}

答えて

2

ファイルを閉じるには、XmlTextWriterを処分する必要があります。これは最高のusing文で行われます。

using(XmlTextWriter writer = new XmlWriter.Create(@"D:\data.xml")) 
{ 
    writer.Formatting = Formatting.Indented; 
    doc.Save(writer); 
} 

あなたはリーダー(IDisposableを実装し、実際には、任意のオブジェクト)と同じパターンを使用する必要があります。

+0

ここにコードを追加できますか? – salman

+0

@salman - 何を追加しますか? – Oded

+0

"実際には、IDisposableを実装するオブジェクトはどれですか? – salman

8

あなたは作家クローズする必要があります。

doc.Save(writer); 
writer.Close(); 

あるいはさらに良いと、それを囲みますusingブロック内:

usingステートメントは、例外安全なCloseを保証します。

同様にリーダーを使用してください。

+1

XmlTextWriter.Createは、このオブジェクトをインスタンス化するのに適したメソッドです。 http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.create.aspx – ScottE

+1

+1、それを処分することもできます。 (var writer = new XmlTextWriter(...)) ' – orip

+0

実際には、作者の作成に' Create'を使うだけでなく、廃止された 'XmlTextWriter'ではなく' XmlWriter'を使うべきです。 –

関連する問題