I am trying to sort files according to their creation time from a specific directory and store them in a string array. But I am getting the error "Cannot implicitly convert type 'System.IO.FileInfo[]' to 'string[]'. Is it not possible the store the data in string array?
Here is my code:
string[] getFiles(string path, string text, string fileExtension)
{
try
{
string searchingText = text;
searchingText = "*" text "*";
string[] filesArray = Directory.GetFiles(path, searchingText, SearchOption.TopDirectoryOnly).Select(f => new FileInfo(f)).OrderBy(f => f.CreationTime).ToArray();
//filesArray = filesArray.OrderBy(s => s.).ToArray();
//string[] filesArray2 = Array.Sort(filesArray);
List<string> filesList = new List<string>(filesArray);
List<string> newFilesList = new List<string>();
foreach(string file in filesList)
{
if ( file.Contains(fileExtension) == true)
{
newFilesList.Add(file);
}
}
string[] files = newFilesList.ToArray();
return files;
}
catch
{
string[] files = new string[0];
return files;
}
}
CodePudding user response:
Where are you getting that error? The error is pretty self-explanotory: your function returns an array of strings, and you cannot simply cast a string to a FileInfo object. In order to get a FileInfo object, use:
var fi = new FileInfo(fileName);
However, if all you want is to get a sorted list, I'd go about this differently, for example:
var folder = @"C:\temp";
var files = Directory
.EnumerateFiles(folder)
.OrderBy(x => File.GetCreationTime(x))
.ToArray();
This will give you a list of strings holding file names, sorted by their creation date.
Edit:
If you'd only want files with a given extension, you could expand the LINQ query:
var files = Directory
.EnumerateFiles(folder)
.Where(x => x.EndsWith(".ext"))
.OrderBy(x => File.GetCreationTime(x))
.ToArray();