cannot convert from 'string[]' to 'string'

3413 views c#
-2

        string[] files = Directory.GetFiles(ofd.SelectedPath);
        System.IO.Path.GetFileNameWithoutExtension(files);

So, I get an error saying cannot convert from 'string[]' to 'string'

Is there any way I can Fix this?

answered question

string[] denotes an array, i think you need to identify the correct index before you can get the string method.

GetFileNameWithoutExtension takes a single filename. GetFiles returns an array (i.e. many).

2 Answers

7

The files is an array of string and GetFileNameWithoutExtension accepts a parameter of type string. You need to iterate through files via forach or with LINQ, something like this:

var result = files.Select(System.IO.Path.GetFileNameWithoutExtension);

posted this
12

According to that GetFileNameWithoutExtension function doc it requires a parameter of type string but you are passing a string[] to that method.

If you expect that array to contain only one element, you can call that function this way.

string fileName = System.IO.Path.GetFileNameWithoutExtension(files[0]);

posted this

Have an answer?

JD

Please login first before posting an answer.