【问题标题】:Get all files from folder and their infromation从文件夹中获取所有文件及其信息
【发布时间】:2018-10-30 17:15:51
【问题描述】:

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

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

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

现在我想用示例文件的信息创建这个类的列表。类变量的示例是: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 语句无法对 StorageFile 类型的变量进行操作,因为 StorageFile 不包含 GetEnumerator 的公共定义”

【问题讨论】:

    标签: c# uwp storage


    【解决方案1】:

    DirectoryInfo().GetFiles() 返回一个 FileInfo() 数组,其中包含您需要的所有信息,因此您可以以任何您喜欢的方式从中进行选择:

    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&lt;FileElements&gt;,但是可以在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();
    

    【讨论】:

    • Path.GetFilenameWithoutExtension 比那个Split好。 (例如 Filename.someothertext.txt)
    • @Steve 你是绝对正确的,我编辑了我的答案。
    • 此时我想知道。当有 FileInfo 时,他真的需要一个 FileElements 类吗?
    • @Steve 他需要 FileElements,这正是我的想法,但我认为他可能需要以特定格式保存它,制作一个 json,...
    • @AshkanMobayenKhiabani 谢谢你。不过我还有一个问题。我将如何获得 result[0] 中的信息?例如 var r = result[0] 不是正确的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    • 2015-02-16
    • 2019-06-19
    相关资源
    最近更新 更多