0

我正在尝试将我的数据输出到控制台屏幕和文本文件。我有点卡住了,希望有人能帮忙。我在 Main() 上获得了一些帮助来解析我的文件并为我设置了一个类来指导我完成,但仍然不确定如何将信息显示到屏幕和文本文件中。我的代码如下。

namespace ConsoleApp1
{

class Program
{
    static void Main(string[] args)
    {        

    }

    void Main()
    {
        var lines = ReadFile();

        lines.ToList().ForEach(Console.WriteLine);
    }

    IEnumerable<Line> ReadFile()
    {
        using (var reader = new StreamReader(File.OpenRead(@"C:List.txt")))
        {
            const string directoryPrefix = " Directory of ";
            Regex splittingRegex = new Regex(@"\s+", RegexOptions.Compiled);
            string directory = null;
            string line;

            while ((line = reader.ReadLine()) != null)
            {
                line = line.TrimEnd();
                if (line.StartsWith(directoryPrefix))
                {
                    directory = line.Substring(directoryPrefix.Length);
                    continue;
                }

                var lineParts = splittingRegex.Split(line, 6);
                yield return new Line { Date = lineParts[0], Time = lineParts[1], Period = lineParts[2], Bytes = lineParts[3], User = lineParts[4], Filename = Path.Combine(directory, lineParts[5]) };
            }
        }
    }

    class Line
    {
        private string date;
        private string time;
        private string period;
        private string bytes;
        private string user;
        private string filename;

        public string Date { get { return date; } set { date = value; } }
        public string Time { get { return time; } set { time = value; } }
        public string Period { get { return period; } set { period = value; } }
        public string Bytes { get { return bytes; } set { bytes = value; } }
        public string User { get { return user; } set { user = value; } }
        public string Filename { get { return filename; } set { filename = value; } }
    }
}

}

4

3 回答 3

1

只需将 Main() 方法更改为:

    private void Main()
    {
        var lines = ReadFile().Select(l => l.ToString()).ToList();

        // The short way, do them after each other
        lines.ForEach(Console.WriteLine);
        File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);
    }

并覆盖 Line 类中的 ToString() 方法。

private class Line
{
    public string Date { get; set; }
    public string Time { get; set; }
    public string Period { get; set; }
    public string Bytes { get; set; }
    public string User { get; set; }
    public string Filename { get; set; }

    public override string ToString()
    {
        // Just an example, you could create an other implementation
        return string.Format("Filename: {0} -  Date: {1}", Filename, Date);
    }
}
于 2013-08-28T18:26:55.813 回答
0

您可以使用此开源项目中的 EchoStream:http: //www.codeproject.com/Articles/3922/EchoStream-An-Echo-Tee-Stream-for-NET

于 2013-08-28T18:34:05.413 回答
0

当你输出每一行时,你什么也没做。你应该做这个:

lines.ToList().ForEach(l => Console.WriteLine(l.User));
于 2013-08-28T18:18:43.380 回答