Trying to write the xml file with FileStream.BeginWrite() method but it gives me an Can Not Access the Close File error
My Code is
public void WriteXmlLog(string logType, string logFlag, string logModule, string logLocation, string logText, string logStackTrace)
{
if (!File.Exists(_logFilePath))
{
File.WriteAllText(_logFilePath, "<?xml version='1.0' encoding='utf-8' standalone='yes'?>\r\n<AppXmlLogWritter></AppXmlLogWritter>");
}
XmlDocument xmlDoc = new XmlDocument();
using (fileStream = new FileStream(_logFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
string currentDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
xmlDoc.Load(fileStream);
XmlElement newelement = xmlDoc.CreateElement("LogData");
XmlElement xmlLogID = xmlDoc.CreateElement("LogID");
XmlElement xmlLogDateTime = xmlDoc.CreateElement("LogDateTime");
XmlElement xmlLogType = xmlDoc.CreateElement("LogType");
XmlElement xmlLogFlag = xmlDoc.CreateElement("LogFlag");
XmlElement xmlLogApplication = xmlDoc.CreateElement("LogApplication");
XmlElement xmlLogModule = xmlDoc.CreateElement("LogModule");
XmlElement xmlLogLocation = xmlDoc.CreateElement("LogLocation");
XmlElement xmlLogText = xmlDoc.CreateElement("LogText");
XmlElement xmlLogStackTrace = xmlDoc.CreateElement("LogStackTrace");
xmlLogID.InnerText = _logIDPrefix + currentDateTime + randomNumber;
xmlLogDateTime.InnerText = currentDateTime;
xmlLogType.InnerText = ((LogTypes)Convert.ToInt32(logType)).ToString();
xmlLogFlag.InnerText = logFlag;
xmlLogApplication.InnerText = _logApplication;
xmlLogModule.InnerText = logModule;
xmlLogLocation.InnerText = logLocation;
xmlLogText.InnerText = logText;
xmlLogStackTrace.InnerText = logStackTrace;
newelement.AppendChild(xmlLogID);
newelement.AppendChild(xmlLogDateTime);
newelement.AppendChild(xmlLogType);
newelement.AppendChild(xmlLogFlag);
newelement.AppendChild(xmlLogApplication);
newelement.AppendChild(xmlLogModule);
newelement.AppendChild(xmlLogLocation);
newelement.AppendChild(xmlLogText);
xmlDoc.DocumentElement.AppendChild(newelement);
Byte[] myByteArray = Encoding.UTF8.GetBytes(newelement.ToString());
fileStream.BeginWrite(myByteArray, 0, myByteArray.Length, WriteAsyncCallback, new LogWritter(myByteArray, fileStream));
}
xmlDoc.Save(_logFilePath);
}
public Stream MyStream { get; set; }
private void WriteAsyncCallback(IAsyncResult ar)
{
LogWritter info = ar.AsyncState as LogWritter;
info.MyStream.EndWrite(ar);
}
WriteAsyncCallback(IAsyncResult ar) function gives me the error above.
You’ve got the stream open in a
using()statement, but the last thing you do in that statement is issue an async write. Well, as soon as you issue the async write, the using statement will terminate and your file will close, very likely before the async write happens. Don’t do an async write here. It’s not going to gain you anything, unless you keep the file open and have a handler to close it after the async write completes.