Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a FileInfo array into a String array C#

Tags:

c#

file-io

I create 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 holds all the file names in folder = DirPath

I thought of looping through the FileInfo array and copy it to a String array. Is this ok or is there a much cleaner method ?

like image 368
klijo Avatar asked Dec 27 '11 12:12

klijo


3 Answers

Using LINQ:

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

Alternatively, using Directory you can get filenames directly.

string[] fileList = Directory.GetFiles(DirPath, "*.*", 
                                       SearchOption.AllDirectories);
like image 71
Oded Avatar answered Nov 13 '22 06:11

Oded


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

string[] files;
var fileInfos = files.Select(f => new FileInfo(f));
List<FileInfo> infos = fileInfos.ToList<FileInfo>();
like image 38
Jason Axelson Avatar answered Nov 13 '22 06:11

Jason Axelson


the linq is a great soluction, but for the persons 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;
    }
like image 41
Leonardo Avatar answered Nov 13 '22 06:11

Leonardo