C#调用File.WriteAllLines时报string转IEnumerable<string>错误如何解决
错误原因
File.WriteAllLines() 方法的第二个入参要求传入IEnumerable<string>类型的可枚举字符串集合(比如字符串数组、List<string>等),你当前传入的text是单个string类型变量,类型不匹配所以触发编译错误。
方案1:更换适配单字符串写入的方法
直接用File.WriteAllText(),这个方法原生支持直接传入单个字符串作为写入内容,完全匹配你当前的需求:
Console.WriteLine("Write Some text"); string text = Console.ReadLine(); File.WriteAllText("Text.txt" , text);
方案2:包装为集合后继续使用File.WriteAllLines()
如果需要保留WriteAllLines的调用逻辑,把单个字符串包裹成字符串数组即可:
Console.WriteLine("Write Some text"); string text = Console.ReadLine(); File.WriteAllLines("Text.txt" , new string[] { text });
内容的提问来源于stack exchange,提问作者user16747424
相关产品推荐
相关产品推荐

