简体   繁体   中英

Cannot implicitly convert fileinfo[] to string[] in c#

I have this line in c# that I need to modify, currently it is working fine

 string[] UploadFilesList = new DirectoryInfo(UploadFolder)
         .GetFiles()
         .Select(o => o.Name.Replace(".txt", ""))
         .ToArray();

I am not the one who wrote this code. what I want to do is not to replace.txt with anything.

so I did this

string[] UploadFilesList = new DirectoryInfo(UploadFolder)
        .GetFiles()
        .Select(o => o)
        .ToArray();

but getting this error

Cannot implicitly convert fileinfo[] to string[] in c#

I changed the code again to

string[] UploadFilesList = new DirectoryInfo(UploadFolder)
        .GetFiles()
        .ToArray();

but still same error, how to fix this?

In your first code snippet, you are selecting file name of each file and then replacing the extension.

In your second and third code snippet, you are getting all files from DirectoryInfo and trying to store it in the string[] , but

DirectoryInfo().GetFiles() returns an array of type FileInfo

Because of this reason you are getting an error Cannot implicitly convert fileinfo[] to string[]


If you want an array of name of upload files, then try below,

string[] UploadFilesList = new DirectoryInfo(UploadFolder)
           .GetFiles()          //Provide list of files from given. directory
           .Select(x => x.Name) //Select only Name from each FileInfo. Do not replace an extension
           .ToArray();          //Convert to an array.

the compiler is telling you that your are trying to store Files in an array of strings which is not possible, to get an array of strings just select the Name property instead of all the File.

.select(o=>o.name).toArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM