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?
CodePudding user response:
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 typeFileInfo
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.
CodePudding user response:
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();