0

同じxmlRequestPathおよびxmlResponsePathファイルを使用して、ループ内で以下のメソッドを呼び出しています。3回目の繰り返しで2回のループカウントが正常に実行されます「別のプロセスで使用されているため、プロセスはファイルにアクセスできません。」という例外が発生します。

    public static void UpdateBatchID(String xmlRequestPath, String xmlResponsePath)
    {
        String batchId = "";
        XDocument requestDoc = null;
        XDocument responseDoc = null;
        lock (locker)
        {
            using (var sr = new StreamReader(xmlRequestPath))
            {
                requestDoc = XDocument.Load(sr);
                var element = requestDoc.Root;
                batchId = element.Attribute("BatchID").Value;

                if (batchId.Length >= 16)
                {
                    batchId = batchId.Remove(0, 16).Insert(0, DateTime.Now.ToString("yyyyMMddHHmmssff"));
                }
                else if (batchId != "") { batchId = DateTime.Now.ToString("yyyyMMddHHmmssff"); }
                element.SetAttributeValue("BatchID", batchId);
            }

            using (var sw = new StreamWriter(xmlRequestPath))
            {
                requestDoc.Save(sw);
            }

            using (var sr = new StreamReader(xmlResponsePath))
            {
                responseDoc = XDocument.Load(sr);
                var elementResponse = responseDoc.Root;
                elementResponse.SetAttributeValue("BatchID", batchId);

            }

            using (var sw = new StreamWriter(xmlResponsePath))
            {                    
                responseDoc.Save(sw);                    
            }
        }
        Thread.Sleep(500);

        requestDoc = null;
        responseDoc = null;
    }

using (var sw = new StreamWriter(xmlResponsePath))上記のコードで例外が発生しています。

例外:

The process cannot access the file 'D:\Projects\ESELServer20130902\trunk\Testing\ESL Server Testing\ESLServerTesting\ESLServerTesting\TestData\Assign\Expected Response\Assign5kMACResponse.xml' because it is being used by another process.

4

2 に答える 2

0

書き込みストリームと読み取りストリームの 2 つのストリームを使用する代わりに、FileStream のみを使用してみてください。問題は、ファイルをロードした後、ガベージ コレクターがアクティブになるまでストリームが開いたままになる可能性があるためです。

using (FileSteam f = new FileStream(xmlResponsePath))
{
     responseDoc = XDocument.Load(sr);

     var elementResponse = responseDoc.Root;
     elementResponse.SetAttributeValue("BatchID", batchId);

     responseDoc.Save(sw);                    
}
于 2014-06-24T12:49:40.307 に答える