How to perform Multiple write opeartion on a single file?
I have a website in asp.net 2.0 which write some thing on a file. But at the same time if another user hit that site it does not work till the first one operation on the file completed after that second one can do operation with the files. How to handle such situation.
AppConfiguration appConfiguration = new AppConfiguration();
string LogFile =String.Empty;
string sLogFormat =string.Empty;
string sErrorTime =string.Empty;
StreamWriter sw=null;
public LogManager()
{
if(!File.Exists(AppConfiguration.LogFilePath))
{
Directory.CreateDirectory(AppConfiguration.LogFilePath);
}
LogFile = AppConfiguration.LogFilePath+"WAP"+sErrorTime + ".log";
if(!File.Exists(LogFile))
{
File.Create(LogFile);
}
}
public void closeStream()
{
if(sw != null)
{
sw.Close();
}
}
public void LogException(string className,string methodName, string errorMessage)
{
try
{
if(!File.Exists(LogFile))
{
File.Create(LogFile);
}
sw = new StreamWriter(LogFile,tru开发者_运维技巧e);
sw.WriteLine(DateTime.Now.ToString() + " | " + className + ":" + methodName + ":"+ errorMessage);
sw.Flush();
sw.Close();
}
catch(Exception)
{
if(sw != null)
{
sw.Close();
}
}
}
Rather than opening and closing the log file for every entry, you might consider having a single logging process (e.g. syslog or a separate logging thread) that keeps the log file open.
Writing lines to a plain text file will mess it up if multiple users are going to handle it. Rather, you can use database to store / retrieve text. You can even provide a button somewhere to export the records to a plain text file if needed.
精彩评论