简体   繁体   中英

C#, cannot convert from 'System.Collections.Generic.IEnumerable' to 'string[]'

I have some C# code:

var oldLines = System.IO.File.ReadAllLines(path);
var newLines = oldLines.Where(line => !line.Contains(wordToDelete));
System.IO.File.WriteAllLines(path, newLines);

The code works in a new windows application. But when I paste that code into my existing app, I get these errors:

Error   2   Argument 2: cannot convert from
'System.Collections.Generic.IEnumerable<string>' to 'string[]'
Error   1   The best overloaded method match for
'System.IO.File.WriteAllLines(string, string[])' has some invalid
arguments

Why would this error be thrown in a new project, but not in my old project?

oldLines.Where(line => !line.Contains(wordToDelete)); returns a IEnumerable< string>

System.IO.File.WriteAllLines(path, newLines.ToArray());

will fix it,

This is probably caused by another framework version target.

newLines is an IEnumerable<string> not a string[] , but your .NET version (I assume 3.5) does not have the overload which accepts an IEnumerable<String> , that was introduced in .NET 4.

So you just need to create a string[] for File.WriteAllLines or use at least .NET 4:

System.IO.File.WriteAllLines(path, newLines.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