c# - 选择要删除的文件。要删除,请键入文件否文件号 示例 3 1
问题描述
需要删除数组中的多个文件无法弄清楚如何
Console.WriteLine("Select file to delete To delete,type file No<space>file No. example 3 1");
string bye = Console.ReadLine();
foreach(FileInfo f in fiArr)
{
File.Delete(f.FullName);
}
此代码将删除数组中的所有文件我需要它只删除数组中的选定文件
解决方案
一种方法是将用户输入转换为整数数组,然后对于他们输入的每个整数,使用整数索引从我们的文件数组中删除该项目。
我从用户输入的每个索引中减去 1,因为数组是从零开始的。因此,如果用户输入1
删除第一个项目,我们要删除 index 处的项目0
。
请注意,由于您似乎有一个FileInfo
对象数组,因此我Delete()
在对象本身上调用该方法:
int temp = 0;
// Convert input string to an integer array by splitting on the space character and
// using int.TryParse to convert the entry to an integer.
// Also, since arrays are zero-based, we subtract 1 from the input value.
// Finally, we only select integers that are valid indexes in our file array.
int[] indexesToDelete = bye
.Split(' ')
.Where(item => int.TryParse(item, out temp) && temp > 0 && temp <= fiArr.Length)
.Select(x => temp - 1)
.ToArray();
// For each index, call 'Delete' on that object
foreach(int index in indexesToDelete)
{
fiArr[index].Delete();
}
推荐阅读
- reactjs - 打字稿界面中的反应组件是什么?
- angular - 当我点击复选框时,我想显示文本框?
- c# - 在 Entity Framework Core 中调用返回标量值的存储过程
- python - 如何计算一列的累积和并创建一个新列?
- android - Jetpack 用图像奇怪的问题组成动画
- java - 如何编写 PCollection
>> 使用 java OutputStream 进入多个文件 - php - PHP 或 Apache/Nginx 服务器中的白名单域
- c++ - QueryFullProcessImageName 未在此范围内声明
- javascript - 有没有办法使用 selenium 从 Python 中的 Javascript 调用中获取项目列表?
- getstream-io - 用户类型 getstream-io