[英]Get all files from folder and their infromation
因此,我通過UWP創建了sample.txt
,並在UWP App的本地文件夾中復制/ sample2.pdf
了sample2.pdf
和sample3.mp4
。
所以現在我的文件夾中有這三個文件。
然后我創建了一個類,該類應保存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的公共定義”
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<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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.