计算目录中的图像文件

时间:2014-04-17 11:18:14

标签: vb.net import .net getfiles

我试图枚举并导入文件夹中的大量图像文件。我目前计算图像的代码如下 -

Dim fullpath As String
fullpath = TxtPath.Text + "\"


Dim FileDirectory As New IO.DirectoryInfo(fullpath)
Dim FileJpg As IO.FileInfo() = FileDirectory.GetFiles("*.jpg")
Dim FileJpeg As IO.FileInfo() = FileDirectory.GetFiles("*.jpeg")
Dim FileGif As IO.FileInfo() = FileDirectory.GetFiles("*.gif")
Dim FileBmp As IO.FileInfo() = FileDirectory.GetFiles("*.bmp")
Dim FilePng As IO.FileInfo() = FileDirectory.GetFiles("*.png")

Dim count As Integer = 0

For Each File As IO.FileInfo In FileJpg
    count += 1
Next
For Each File As IO.FileInfo In FileJpeg
    count += 1
Next
For Each File As IO.FileInfo In FileGif
    count += 1
Next
For Each File As IO.FileInfo In FileBmp
    count += 1
Next
For Each File As IO.FileInfo In FilePng
    count += 1
Next

是否有更有效的方法在一个For循环中执行此操作,而不是5个单独的循环 - 是否可以向GetFiles发送文件扩展名数组?

我还计划使用此代码将这些图像导入数据库,因此在一个循环中也可以提高效率。

谢谢!

2 个答案:

答案 0 :(得分:3)

不是最好的解决方案,但我现在没有时间参加LINQ。试试这个:

Dim extensions As New List(Of String)
extensions.Add("*.png")
' And so on, until all are in...

Dim fileCount As Integer
For i As Integer = 0 To extensions.Count - 1
  fileCount += Directory.GetFiles(txtPath.Text, extensions(i), SearchOption.AllDirectories).Length
Next

答案 1 :(得分:1)

我看了VB.NET已经有一段时间了,但是在C#中你可以这样做:

    static void Main(string[] args)
    {
        string filePath = @"I:\Archive\2009.12.21c";

        List<string> extensions = new List<string>{
            ".jpg",
            ".jpeg",
            ".png",
        };

        string[] countImages = System.IO.Directory.GetFiles(filePath);

        foreach (string file in countImages)
        {
            if (extensions.Contains(System.IO.Path.GetExtension(file).ToLowerInvariant()))
            {
                //This is where you can add to your count for found files
            }
        }
    }

这些都是.NET类,应该很容易转换回VB.NET。


编辑@Trade

@Trade好的,能够得到它。把你的代码(转换为C#)和我的代码,6循环我的然后你的,然后再6你的我的。你的6次跟随6次穿过我的,然后翻转它们(所有以确保不是JIT热身)和结果:差异超过我使用的方法的一个数量级:

示例:你的是enum2,我的是enum1

Found 37 with dir enum1 in 609
Found 37 with dir enum1 in 469
Found 37 with dir enum1 in 462
Found 37 with dir enum1 in 455
Found 37 with dir enum1 in 448
Found 37 with dir enum1 in 406
Found 37 with dir enum2 in 6314
Found 37 with dir enum2 in 6888
Found 37 with dir enum2 in 5439
Found 37 with dir enum2 in 5614
Found 37 with dir enum2 in 5824
Found 37 with dir enum2 in 6342

以下是您的方法的转换代码:

private static void enum2(string filePath, List<string> extensions)
{
    System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
    sw.Start();
    int countCount = 0;
    for (int i = 0; i < extensions.Count(); i++)
    {
        string curExt = extensions[i];
        countCount += System.IO.Directory.GetFiles(filePath, "*" +
            curExt, System.IO.SearchOption.TopDirectoryOnly).Length;
    }
    sw.Stop();

    Console.WriteLine("Found {0} with dir enum2 in {1}",
        countCount, sw.ElapsedTicks.ToString());
}