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

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

以下是错误代码:

cs 复制代码
 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博客

相关推荐
蔡蓝4 分钟前
设计模式-观察着模式
java·开发语言·设计模式
西北大程序猿1 小时前
单例模式与锁(死锁)
linux·开发语言·c++·单例模式
你不是我我1 小时前
【Java开发日记】说一说 SpringBoot 中 CommandLineRunner
java·开发语言·spring boot
心扬1 小时前
python网络编程
开发语言·网络·python·tcp/ip
qq_454175791 小时前
c++学习-this指针
开发语言·c++·学习
Rose 使者2 小时前
全球IP归属地查询接口如何用C#进行调用?
c#·api·ip地址
尘浮7282 小时前
60天python训练计划----day45
开发语言·python
sss191s2 小时前
校招 java 面试基础题目及解析
java·开发语言·面试
sduwcgg2 小时前
python的numpy的MKL加速
开发语言·python·numpy
钢铁男儿2 小时前
Python 接口:从协议到抽象基 类(定义并使用一个抽象基类)
开发语言·python