C# FileInfo Array to String Array

2019-07-29 22:28发布

I have an array that stores files from a directory:

    string pathToDirectory = @"C:\files";
    System.IO.DirectoryInfo diDir = new DirectoryInfo(pathToDirectory);
    System.IO.FileInfo[] File_Array = diDir.GetFiles();

    foreach (FileInfo lfileInfo in File_Array)
    {
    }   

I want to try and convert this array into a string type array instead of a FileInfo type. Please let me know how I can go about doing this. Any help would be greatly appreciated.

2条回答
啃猪蹄的小仙女
2楼-- · 2019-07-29 23:01

Use static Directory class instead. It returns files as strings instead of instantiating FileInfo instances which you don't need

string[] files = Directory.GetFiles(pathToDirectory);

If you want just file names without path, then use Path to get rid of directory path:

var fileNames = Directory.GetFiles(pathToDirectory)
                         .Select(Path.GetFileName);
查看更多
Rolldiameter
3楼-- · 2019-07-29 23:08
string[] fileNames = File_Array.Select(f => f.Name).ToArray();
查看更多
登录 后发表回答