Question

here's my code

class Program
{
    static void Main(string[] args)
    {
        (from d in new DirectoryInfo("E:\\")
    .GetDirectories() select d.Name)
             .WriteToConsole(Logger.WriteToLog , true);
            //    .WriteToConsole(Console.WriteLine);
    }
}

public static class Logger
{
    public static void WriteToLog(dynamic data)
    {
        string filePath = string.Format("{0}\\log.txt", Environment.CurrentDirectory);
        var stream = File.Create(filePath);
        stream.Write(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetByteCount(data));
        stream.Flush();
        stream.Close();
    }
}

public static class WriteExtensions
{
    public static void WriteToConsole<T1>(this IEnumerable<T1> data , Action<T1> action, bool carelist = false)
    {
        if (carelist)
        {
            // all i want is to invoke action by sending data rather than
    // one by one
            return;
        }
        foreach (var item in data)
        {
            action.Invoke(item);
        }
    }
}

problem is we can write to console line by line..but for writing to file i want to put all at once .. any help.. thanks

Était-ce utile?

La solution

Your logging requirements are revealing to be complex. Therefore I suggest already existing logging frameworks. They have functionalities that you need, but maybe don't yet realize that you need them. Logging to console and log file are supported, and can be enabled in configuration file, instead of in code directly. Also logging to several targets at the same time. Also filtering based on severity of the log. Also rollover to another file when date changes, or file grows over the limit.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top