Thursday, June 7, 2012

ASP.NET(Write txt log file in daily basis)


public static void WriteLog(string strError, string MethodName, string parameters, string pageName)
    {
        string FileName = HttpContext.Current.Server.MapPath("Path/logs_" + DateTime.Now.ToString("yyyyMMdd") + ".txt");
        string strText = DateTime.Now.ToString() + "\t" + pageName + "\t\t" + MethodName + "\t" + parameters + "\t" + strError;

        if (!File.Exists(FileName))
        {
            // Create New Text File
            FileStream fStream = new FileStream(FileName, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fStream);
            sw.WriteLine(strText);
            sw.Close();
            fStream.Close();

        }
        else
        {
            FileInfo finfo = new FileInfo(FileName);

            while (IsFileLocked(finfo))
            {
                Thread.Sleep(500);
            }

            finfo = null;

            FileStream aFile = new FileStream(FileName, FileMode.Append, FileAccess.Write);
            StreamWriter sw = new StreamWriter(aFile);
            sw.WriteLine(strText);
            sw.Close();
            aFile.Close();
        }
    }



    private static bool IsFileLocked(FileInfo file)
    {
        FileStream stream = null;

        try
        {
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            //the file is unavailable because it is:
            //still being written to
            //or being processed by another thread
            //or does not exist (has already been processed)
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }

        //file is not locked
        return false;
    }

No comments:

Post a Comment