我在具有相同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 回答
也许在第三个循环中,流仍处于关闭状态,因此它告诉您它不可访问 . 在循环中再次调用它之前尝试等待,例如:
或者,显式关闭流而不是将工作留给垃圾收集器:
而不是使用两个流,Write和Read流,请尝试仅使用FileStream,因为问题可能是在加载文件后,流保持打开,直到garbadge收集器激活 .