-4

I have an array with items having names with .txt. I want to remove the extension. The following code is not working.

var xx = filenames.ForEach(x => { int fileExtPos = x.LastIndexOf("."); if (fileExtPos >= 0) x = x.Substring(0, fileExtPos); }); 

Can anyone help what am i doing wrong here?

Thanks

4
  • You can use Path.GetFileNameWithoutExtension("filename") Commented Sep 27, 2018 at 13:23
  • "The following code is not working." -- Why is it not working? Is there an error? Are the results wrong? Also, in the future dont use the .ForEach() extension method. Use a foreach loop Commented Sep 27, 2018 at 13:23
  • 1
    It would be awesome if you could provide a minimal reproducible example. For example, I am surprised if the above code compiles if filenames is an array. Also, do you want the filenames (without extension) to be written back to the array? Or do you want to project that to a new list / array? Or something else? Commented Sep 27, 2018 at 13:26
  • 2
    var names = filenames.Select(Path.GetFileNameWithoutExtension); Commented Sep 27, 2018 at 13:27

1 Answer 1

6

There is a build in method GetFileNameWithoutExtension() which could be used. That's the common way to handle this.

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

You error appears here var xx = filenames.ForEach because ForEach has no return value (void) which could be assigned to var xx.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.