首页 > 解决方案 > 选择要删除的文件。要删除,请键入文件否文件号 示例 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);
    }

此代码将删除数组中的所有文件我需要它只删除数组中的选定文件

标签: c#arrays

解决方案


一种方法是将用户输入转换为整数数组,然后对于他们输入的每个整数,使用整数索引从我们的文件数组中删除该项目。

我从用户输入的每个索引中减去 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();
}

推荐阅读