欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > c# List<string>.Add(s) 报错:UnsupportedOperationException

c# List<string>.Add(s) 报错:UnsupportedOperationException

2025/6/12 19:31:43 来源:https://blog.csdn.net/lz576825608/article/details/148463456  浏览:    关键词:c# List<string>.Add(s) 报错:UnsupportedOperationException

在使用c#读取目录下指定格式文件目录后,使用List<string>.Add 来保存文件名时,出现UnsupportedOperationException错误,找了好久不知道问题出在哪里。

以下是错误代码:

 using (var fbd = new FolderBrowserDialog{Description = "选择txt文件目录",ShowNewFolderButton = false,RootFolder = Environment.SpecialFolder.Desktop}){if (fbd.ShowDialog() == DialogResult.OK){try{var sw = Stopwatch.StartNew();// 异步并行扫描var filePaths = Directory.EnumerateFiles(fbd.SelectedPath, "*.*",SearchOption.AllDirectories).Where(f => f.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)).AsParallel().WithDegreeOfParallelism(Environment.ProcessorCount);var files = filePaths.ToList();List<string> ff = new List<string>();foreach (var f in files){//下边ff.Add()报错------------------------ff.Add(Path.GetFileNameWithoutExtension(f));//}sw.Stop();}catch (Exception){}}

在foreach里,给List<string> 赋值,

           ff.Add(Path.GetFileNameWithoutExtension(f));

//以上ff.Add运行后报错:UnsupportedOperationException

查看了数据类型没有问题,难道这个List<T>使用Add方法会有要求,随即将以上代码中的

var files = filePaths.ToList();

修改成了:

var files = filePaths.ToArray();

执行后,既然不报错了。奇怪的问题。

参考:list<string> add()方法 居然报错了_list<string> add-CSDN博客

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词