将日志写入日志文件后,将该文件作为附件发送给电子邮件

时间:2013-10-17 13:48:01

标签: c# winforms

嗨抱歉如果这是一个愚蠢的人。

我创建了一个记录信息的Logger类,我在不同的项目中使用Logger类和记录信息。我有一个要求,我需要在完成写入后发送日志文件的电子邮件附件。

但是文件路径位置在Logger.cs类中如何知道我使用记录器的项目中文件的位置。

** Logger.cs **

public  class Logger
{

    // logFilePath where to write?
    readonly string logFilePath = string.Empty;

    /// <summary>
    /// Constructor
    /// </summary>
    public  Logger()
    {
        String filePath = string.Format("{0:yyyy-MM-dd}", DateTime.Now);

        // This is the text file created with time stamps
        var folderName = ConfigurationManager.AppSettings["FolderToCreate"];
        String txtFile = string.Format("Log{0:yyyy-MM-dd hh-mm-ss-tt}", DateTime.Now);
        // Given in config to read the path 
        var localhostizedLetter = ConfigurationManager.AppSettings["localhostDriveLetter"]+"//";
        //Create directory
        string pathString = Path.Combine(localhostizedLetter, folderName);
        if (!Directory.Exists(pathString))
        {
            Directory.CreateDirectory(pathString);
        }
        // Create a folder inside directory 
        // If folder exists dont create it 
        pathString = Path.Combine(pathString, filePath);
        if (!Directory.Exists(pathString))
        {
            Directory.CreateDirectory(pathString);
        }
        // create a file inside d://DataSummarisationDatetime.now//datetimewithtimestamp.txt
        // if exists please dont create it.
        pathString = Path.Combine(pathString, txtFile);
        if (!Directory.Exists(pathString))
        {
            // here my file is created and opened.
            // so I m doing a try catch to make sure if file is opened we are closing it so that nother process can use it
            File.Create(pathString).Dispose();
            var fileInfo = new FileInfo(pathString);
            IsFileLocked(fileInfo);

        }
        logFilePath = pathString;

        //logFilePath = ConfigurationManager.AppSettings["localhostDriveLetter"] + "\\" + "RetailerfeedLogFiles" + "\\" + string.Format("RetailerFeed{0:yyyy-MM-dd hh-mm-ss-tt}", DateTime.Now) + ".txt";
    }

    /// <summary>
    ///  To check if File is opened by another process.
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    private 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;
    }

    /// <summary>
    /// Log message using textwriter
    /// </summary>
    /// <param name="logMessage"></param>
    /// <param name="w"></param>
    public static void Log(string logMessage, TextWriter w)
    {
        w.Write("\r\n" + DateTime.Now + " " + logMessage);
        w.Flush();
    }

    /// <summary>
    /// Call this function to log your message
    /// </summary>
    /// <param name="textLog"></param>
    public void Log(string textLog)
    {
        StreamWriter sw = null;

        if (!File.Exists(logFilePath))
        {
            try
            {
                sw = File.CreateText(logFilePath);
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                sw.Dispose();
            }

        }
        try
        {

            using (StreamWriter w = File.AppendText(logFilePath))
            {
                Log(textLog, w);

                w.Close();
            }

        }
        catch (Exception exception)
        {

            throw exception;
        }

    }

}

** RetailerFeed.cs **

public partial class RetailerFeeds : Form
{
  private Logger _logger = new Logger();
    _logger.Log("                                ");
            _logger.Log(" Total no.of scrapes/retailers  to Process    :  " + scrapesRun.Count());
            _logger.Log(" Starting RetailerFeeds Processing " );
            _logger.Log("       ");
            _logger.Log(" Processing : " + scrape.Retailer.Description);

_keepItDry.SendRetailerFeedNotification("Ended RetailerFeeds Interface " , stringBuilder.ToString());


}
  • SendRetailerFeedNotification我需要将日志文件作为附件发送*

2 个答案:

答案 0 :(得分:1)

只需更改

readonly string logFilePath = ... ;

public string LogFilePath { get; set; }

并且其值可用于其他代码。

答案 1 :(得分:0)

您只需要更改Logger类以某种方式公开Filepath。

  • 作为公共变量,
  • 作为公共财产,
  • 使用返回Filepath的公共函数

然后您将在主程序中访问它