Reputation: 883
So I created a sample.txt
via UWP and copy/past a sample2.pdf
and a sample3.mp4
in the local folder of my UWP App.
So right now I have those 3 files in my folder.
Then I created a class which should save the filename, extension, id and modifiedDate
Now I want to create a list of this class with the information of the sample files. Example of a class Variable would be: filename = sample, extension = .txt, id = sample, modified date = 30.10.2018 09:00
How would I do that?
My Code so far:
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; }
}
}
I tried to figure it out with the foreach()
methode but it doesnt work
"foreach statement cannot operate on variables of type StorageFile because StorageFile does not contain a public definition for GetEnumerator"
Upvotes: 1
Views: 141
Reputation: 34180
DirectoryInfo().GetFiles()
returns an array of FileInfo()
which contains all information you need, so you can select from it in any way you like:
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()
});
Edit (considering your comment):
the above result is an IEnumerable<FileElements>
that does not support indexing, but it can be used in a foreach loop. however you can convert it to FileElements[] simply by .ToArray()
to be able to use indexing:
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();
Upvotes: 4