从文件夹中获取所有文件及其信息

Get all files from folder and their infromation

所以我通过 UWP 创建了一个 sample.txt,并在我的 UWP 应用程序的本地文件夹中创建了一个 copy/past 一个 sample2.pdf 和一个 sample3.mp4

所以现在我的文件夹中有这 3 个文件。

然后我创建了一个 class 应该保存 filename, extension, id and modifiedDate

现在我想用示例文件的信息创建此 class 的列表。 class 变量的示例为:filename = sample, extension = .txt, id = sample, modified date = 30.10.2018 09:00

我该怎么做?

到目前为止我的代码:

public sealed partial class MainPage : Page
{
    Windows.Storage.StorageFolder storageFolder;
    Windows.Storage.StorageFile sampleFile;
    List<FileElements> fileInformation = new List<FileElements>();

    public MainPage()
    {
        this.InitializeComponent();
        moth();
    }

    async void moth()
    {
        storageFolder =
            Windows.Storage.ApplicationData.Current.LocalFolder;
        sampleFile =
            await storageFolder.CreateFileAsync("sample.txt",
                Windows.Storage.CreationCollisionOption.ReplaceExisting);
    }

    public class FileElements
    {
        public string filename { get; set; }
        public string extension { get; set; }
        public string id { get; set; }
        public string modifiedDate { get; set; }
    }
}

我试图用 foreach() 方法解决这个问题,但它不起作用

"foreach statement cannot operate on variables of type StorageFile because StorageFile does not contain a public definition for GetEnumerator"

DirectoryInfo().GetFiles() returns FileInfo() 的数组,其中包含您需要的所有信息,因此您可以 select 以任何您喜欢的方式从中获取:

var result = System.IO.DirectoryInfo dir = new DirectoryInfo(dirPath);
             dir.GetFiles().Select((x,i) => new FileElements {
                filename = Path.GetFileNameWithoutExtension(x.FullName),
                extension = x.Extension,
                id = i.ToString(),
                modifiedDate = x.LastWriteTime.ToString()
            });

编辑(考虑您的评论):

上面的结果是IEnumerable<FileElements>不支持索引,但是可以在foreach循环中使用。但是你可以简单地通过 .ToArray() 将它转换为 FileElements[] 以便能够使用索引:

var result = System.IO.DirectoryInfo dir = new DirectoryInfo(dirPath);
                 dir.GetFiles().Select((x,i) => new FileElements {
                    filename = Path.GetFileNameWithoutExtension(x.FullName),
                    extension = x.Extension,
                    id = i.ToString(),
                    modifiedDate = x.LastWriteTime.ToString()
                }).ToArray();