Convert FileInfo array to String C # array

I am creating a FileInfo array like this

try { DirectoryInfo Dir = new DirectoryInfo(DirPath); FileInfo[] FileList = Dir.GetFiles("*.*", SearchOption.AllDirectories); foreach (FileInfo FI in FileList) { Console.WriteLine(FI.FullName); } } catch (Exception e) { Console.WriteLine(e.ToString()); } 

And this array contains all the file names in the = DirPath folder

I thought about iterating over the FileInfo array and copying it to the String array. Is this normal or is there a cleaner method?

+6
source share
4 answers

Using LINQ:

 FileList.Select(f => f.FullName).ToArray(); 

Alternatively, using Directory , you can get the file names directly.

 string[] fileList = Directory.GetFiles(DirPath, "*.*", SearchOption.AllDirectories); 
+11
source

If you want to go the other way (convert the string array to FileInfo), you can use the following:

 string[] files; var fileInfos = files.Select(f => new FileInfo(f)); List<FileInfo> infos = fileInfos.ToList<FileInfo>(); 
+2
source

linq is a great solution, but for those who don't want to use linq, I made this function:

  static string BlastWriteFile(FileInfo file) { string blasfile = " "; using (StreamReader sr = file.OpenText()) { string s = " "; while ((s = sr.ReadLine()) != null) { blasfile = blasfile + s + "\n"; Console.WriteLine(); } } return blasfile; } 
+1
source

Try this one

 DirectoryInfo directory = new DirectoryInfo("your path"); List<string> Files = (directory.GetFiles().Where(file => file.LastWriteTime >= date_value)).Select(f => f.Name).ToList(); 

If you don’t need a date filter, you can simply convert using the code below

 List<string> logFiles = directory.GetFiles().Select(f => f.Name).ToList(); 

If you need the full path to the file, you can use FullName instead of Name .

0
source

Source: https://habr.com/ru/post/904532/


All Articles