Печать файлов, измененных за последние 24 часа, на консоль

Я прохожу курс C#, и в настоящее время мне поручено создать консольное приложение, которое передает новые файлы (измененные за последние 24 часа) из каталога "Заказы клиентов" в каталог "Домашний офис".

На данный момент я просто пытаюсь найти способ выяснить, какие файлы новые. Чтобы проверить, работает ли это, я использую Console.WriteLine для печати новых файлов в окне консоли. Однако все, что он делает, это печатает "System.Linq.Enumerable+WhereArrayIterator'1[System.IO.FileInfo]".

Я невероятно новичок в этом языке, и я волнуюсь, что уже все делаю неправильно. Вот мой код (после часа поиска в Google и получения идей от Stackru):

    class ModifiedFiles
    {
        public string your_dir;

        public IEnumerable<FileInfo> modified()
        {
            your_dir = @"C:\Users\Student\Desktop\Customer Orders";
            var directory = new DirectoryInfo(your_dir);
            DateTime from_date = DateTime.Now.AddDays(-1);
            DateTime to_date = DateTime.Now;
            var files = directory.GetFiles()
              .Where(file => file.LastWriteTime >= from_date && file.LastWriteTime <= to_date);
            return files;
        }
    }
    static void Main(string[] args)
    {
        ModifiedFiles newFiles = new ModifiedFiles();
        Console.WriteLine(newFiles.modified());
        Console.ReadLine();
    }

Может кто-то любезно указать, что здесь происходит, и направить меня на правильный путь?

2 ответа

Решение

Что происходит, так это то, что каждый тип в C# наследует ToString метод, который, если не переопределить, выведет строковое представление объекта по умолчанию: его тип имени.

Ссылка:

https://msdn.microsoft.com/en-us/library/system.object.tostring(v=vs.110).aspx

Теперь вот 4 примера, распечатывающих каждое имя файла и показывающих поведение по умолчанию: ToString и переопределенное поведение:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace MyConsole
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var path = Environment.CurrentDirectory;
            var fromDate = DateTime.Now.AddDays(-1);
            var toDate = DateTime.Now;

            var files = MyClass.GetModifiedFiles(path, fromDate, toDate);

            //System.Linq.Enumerable+WhereArrayIterator`1[System.IO.FileInfo]
            Console.WriteLine(files);

            //System.Collections.Generic.List`1[System.IO.FileInfo]
            Console.WriteLine(files.ToList());

            //MyConsole.exe
            //MyConsole.exe.config
            //MyConsole.pdb
            //MyConsole.vshost.exe
            //MyConsole.vshost.exe.config
            foreach (var file in files)
            {
                Console.WriteLine(file.Name);
            }

            //MyConsole.exe
            //MyConsole.exe.config
            //MyConsole.pdb
            //MyConsole.vshost.exe
            //MyConsole.vshost.exe.config    
            var myClass = new MyClass();
            myClass.FindModifiedFiles(path, fromDate, toDate);
            Console.WriteLine(myClass); // .ToString implicitly called

            Console.ReadLine();
        }
    }

    internal class MyClass
    {
        private IEnumerable<FileInfo> _modifiedFiles;

        public void FindModifiedFiles(string path, DateTime fromDate, DateTime toDate)
        {
            _modifiedFiles = GetModifiedFiles(path, fromDate, toDate);
        }

        /* overriding default implemenation of ToString */

        /// <summary>Returns a string that represents the current object.</summary>
        /// <returns>A string that represents the current object.</returns>
        /// <filterpriority>2</filterpriority>
        public override string ToString()
        {
            return string.Join(Environment.NewLine, _modifiedFiles.Select(s => s.Name));
        }

        public static IEnumerable<FileInfo> GetModifiedFiles(string path, DateTime fromDate, DateTime toDate)
        {
            if (path == null) throw new ArgumentNullException(nameof(path));
            var directory = new DirectoryInfo(path);
            var files = directory.GetFiles()
                .Where(file => file.LastWriteTime >= fromDate && file.LastWriteTime <= toDate);
            return files;
        }
    }
}

Согласно комментариям, я добавил .ToList() в оператор возврата моего метода, а затем создал этот цикл foreach в Main:

foreach (var file in newFiles.modified())
{
    Console.WriteLine(file);
}
Другие вопросы по тегам