如何在单个文件上执行多次写操作?

时间:2010-11-22 04:30:42

标签: asp.net file-io

我在asp.net 2.0中有一个网站,它在文件上写了一些东西。但同时如果另一个用户点击该站点,则在该文件的第一个操作完成之后它才能工作,之后第二个操作可以对文件进行操作。 如何处理这种情况。

            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,true);

            sw.WriteLine(DateTime.Now.ToString() + " | " + className + ":" + methodName + ":"+ errorMessage);
            sw.Flush();
            sw.Close();
        }
        catch(Exception)
        {
            if(sw != null)
            {
                sw.Close();
            }
        }

    }

2 个答案:

答案 0 :(得分:0)

您可以考虑使用单个日志记录进程(例如syslog或单独的日志记录线程)来保持日志文件的打开状态,而不是为每个条目打开和关闭日志文件。

答案 1 :(得分:-1)

如果有多个用户要处理它,那么将行写入纯文本文件会弄乱它。相反,您可以使用数据库来存储/检索文本。如果需要,您甚至可以在某处提供按钮以将记录导出为纯文本文件。