1

嗨对不起,如果这是一个愚蠢的。

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

但是文件路径位置在 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 我需要将日志文件作为附件发送 *
4

2 回答 2

1

简单地改变

readonly string logFilePath = ... ;

public string LogFilePath { get; set; }

并且它的值将可用于其他代码。

于 2013-10-17T13:54:55.943 回答
0

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

  • 作为公共变量,
  • 作为公共财产,
  • 带有返回文件路径的公共函数

那么您将可以在主程序中访问它

于 2013-10-17T14:14:36.077 回答