来自字符串的FileInfo数组

时间:2011-10-14 13:18:29

标签: c# arrays fileinfo

目前我使用以下方法获取文件的大小:

FileInfo fileSize = new FileInfo(@"C:\file.txt");
long size = fileSize.Length;

而不是为我想要的每个文件执行此操作,我认为您必须能够使用数组并遍历它们,所以我使用了这个:

FileInfo[] fileSizes = new FileInfo[2];
fileSizes[0] = @"C:\file.txt";
fileSizes[1] = @"C:\file.txt";

现在我不断收到错误“无法将类型'字符串'隐式转换为'System.IO.FileInfo'”。我尝试使用.ToString()但没有骰子,非常感谢任何帮助,谢谢!

3 个答案:

答案 0 :(得分:2)

FileInfo[] fileSizes = new FileInfo[3];
fileSizes[0] = new FileInfo(@"C:\file.txt");
fileSizes[1] = new FileInfo(@"C:\file.txt");
fileSizes[2] = new FileInfo(@"C:\file.txt");

@“C:\ file.txt”是一个字符串,而不是对象本身..

答案 1 :(得分:2)

您不应在FileInfo数组中存储多个文件。要修复错误,您需要执行以下操作:

FileInfo[] fileSizes = new FileInfo[3];
fileSizes[0] = new FileInfo(@"C:\file.txt");
fileSizes[1] = new FileInfo(@"C:\file.txt");
fileSizes[2] = new FileInfo(@"C:\file.txt");

但是,您应该像这样(下面)存储它们并遍历列表并一次加载一个FileInfo

String[] files = new String[3];
files[0] = @"C:\file.txt";
files[1] = @"C:\file.txt";
files[2] = @"C:\file.txt";

foreach (String file in files)
{
    FileInfo info = new FileInfo(file);
    // do something with info.Length
}

答案 2 :(得分:1)

@"C:\file.txt";替换为new FileInfo(@"C:\file.txt");