简体   繁体   English

如何将openFileDialog.FileNames转换为FileInfo []

[英]How to convert openFileDialog.FileNames to FileInfo[]

I have a OpenFileDialog and I want to convert selected file names to a FileInfo[] variable. 我有一个OpenFileDialog ,我想将选定的文件名转换为FileInfo[]变量。

But I don't know how to convert all the selected files in one line code. 但是我不知道如何在一行代码中转换所有选定的文件。

This obviously doesn't work: 这显然行不通:

FileInfo[] files = openFileDialog.FileNames;

Thank you. 谢谢。

The FileInfo class offers a constructor that expects a filename . FileInfo提供了一个期望使用文件名构造函数 Therefore, to get a FileInfo instance for a single filename string , simply call that constructor: 因此,要获取单个文件名stringFileInfo实例,只需调用该构造函数即可:

FileInfo file = new FileInfo(openFileDialog.FileName);

In your case, you want to get an array and have several filename strings, therefore you can use the LINQ extension methods from the Enumerable class : 在您的情况下,您想要获取一个数组并具有多个文件名字符串,因此可以使用Enumerable类中的LINQ扩展方法:

FileInfo[] files = openFileDialog.FileNames.Select(fn => new FileInfo(fn)).ToArray();

Note the additional call to ToArray in the end, as Select will return an IEnumerable<FileInfo> . 最后请注意对ToArray的附加调用,因为Select将返回IEnumerable<FileInfo>

使用LINQ:

FileInfo[] files = openFileDialog.FileNames.Select(f => new FileInfo(f)).ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM