如何在字符串 [] 上将 FileInfo 转换为 FileInfo[]

本文关键字:FileInfo 转换 上将 字符串 | 更新日期: 2023-09-27 18:31:39

我解决了我的问题。但是当我创建构造函数LI变量时出错ListViewItem但我可以在循环foreach使用它吗?

ListViewItem LISTA = default(ListViewItem);
foreach (LISTA in this.lstImgAdded.SelectedItems) {

我正在尝试使用我的代码获取列表文件的长度:

string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop, false);
List<FileInfo> fileInfos = new List<FileInfo>();  
foreach (string filePath in filePaths)
{
    FileInfo f = new FileInfo(filePaths);
    fileInfos.Add(f); 

这显示错误如下:

无法从"字符串[]"转换为"字符串"

如何在字符串 [] 上将 FileInfo 转换为 FileInfo[]

您不能将class转换为该class完全相同的数组。只需使用:FileInfo f = new FileInfo(filePath);为您的foreach

此外,获取"文件列表的长度"将与filePaths.Length相同

如果需要长度,请改用filePaths.Length

如果要填充FileInfo,请改为执行以下操作:

string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop, false);
List<FileInfo> fileInfos = new List<FileInfo>();    
foreach (string filePath in filePaths)
{
    FileInfo f = new FileInfo(filePaths);
    fileInfos.Add(f);
    //long s1 = f.Length;
}

您的所有文件信息都将在fileInfos中,如果您需要列表中的项目数量,请按照以下步骤CountfileInfos.Count

只需在foreach循环中将filePaths更改为filePath

FileInfo f = new FileInfo(filePath);

另一种方法是像这样更改循环:

foreach (int s1 in filePaths.Select(filePath => new FileInfo(filePath)).Select(f => ((FileInfo[]) f).Length))
{
  //Do somthing with the s1 here
}