该进程无法访问该文件,因为该文件正由另一个进程使用。 XML

时间:2013-11-06 06:16:32

标签: c# xml

我在具有相同xmlRequestPath和xmlResponsePath文件的循环中调用下面的方法。两个循环计数它在第三次迭代中执行正常我得到异常“进程无法访问该文件,因为它正被另一个进程使用。”。

    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.

2 个答案:

答案 0 :(得分:0)

也许在第三个循环中,流仍处于关闭状态,因此它告诉您它不可访问。在循环中再次调用它之前尝试等待,例如:

while (...)
{
    UpdateBatchID(xmlRequestPath, xmlResponsePath);
    System.Threading.Thread.Sleep(500);
}

或者,明确关闭流而不是将工作留给垃圾收集器:

var sr = new StreamReader(xmlResponsePath);
responseDoc = XDocument.Load(sr);
     ....
sr.Close();

答案 1 :(得分:0)

不使用两个流,即Write和Read流,而是尝试仅使用FileStream,因为问题可能是在加载文件后,流保持打开状态,直到garbadge收集器激活。

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

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

     responseDoc.Save(sw);                    
}