2013-06-28 62 views
1

我想有一些代码执行以下操作:测试一个文件夹中的每个文件是JPEG

foreach(File in Directory) 
{ 
    test to see if the file is a jpeg 
} 

,但我不熟悉如何从文件中读取。我该怎么做呢?

+1

http://stackoverflow.com/questions/12332451/c-sharp-list-all-files-和目录中的目录子目录---这是否回答你的问题? – crowder

+0

如果Jonathans的答案不是你的后面,那么directory.getfiles()。All(x => x.fileextension == jpg));语法可能稍微偏离这里 – Sayse

+0

你想知道它是一个有效的jpeg文件,或只是它有一个JPEG扩展? –

回答

1

如果你靶向.NET 4 Directory.EnumerateFiles可能更有效,特别是对于较大的目录。如果没有,您可以将EnumerateFiles替换为GetFiles

//add all the extensions you want to filter to this array 
string[] ext = { "*.jpg", "*.jpeg", "*.jiff" }; 
var fPaths = ext.SelectMany(e => Directory.EnumerateFiles(myDir, e, SearchOption.AllDirectories)).ToList(); 

一旦你有了正确的扩展名的文件的列表,你可以检查,如果该文件实际上是一个JPEG(而不是仅仅被改名.jpg)通过使用在this answer提到的两种不同的方法。 (从这个职位)

static bool HasJpegHeader(string filename) 
{ 
    using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open))) 
    { 
     UInt16 soi = br.ReadUInt16(); // Start of Image (SOI) marker (FFD8) 
     UInt16 jfif = br.ReadUInt16(); // JFIF marker (FFE0) 

     return soi == 0xd8ff && jfif == 0xe0ff; 
    } 
} 

或者更准确的,但速度较慢,方法

static bool IsJpegImage(string filename) 
{ 
    try 
    { 
     System.Drawing.Image img = System.Drawing.Image.FromFile(filename); 

     // Two image formats can be compared using the Equals method 
     // See http://msdn.microsoft.com/en-us/library/system.drawing.imaging.imageformat.aspx 
     // 
     return img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg); 
    } 
    catch (OutOfMemoryException) 
    { 
     // Image.FromFile throws an OutOfMemoryException 
     // if the file does not have a valid image format or 
     // GDI+ does not support the pixel format of the file. 
     // 
     return false; 
    } 
} 

如果有一个机会,你有JPEG文件不具有正确的扩展名,那么你将有循环浏览目录中的所有文件(使用*.*作为过滤器),并对其执行上述两种方法之一。

+0

经过多次测试,看起来像你是我需要的答案。感谢您在这方面的时间和精力。以下是我最终得到的结果: 'var fPaths = ext.SelectMany(a => Directory.EnumerateFiles(filepath,a,SearchOption.AllDirectories))。ToList(); (int i = 0; i TK421

+0

不客气,很高兴你的工作:) – keyboardP

2

为什么不使用Directory.GetFiles()只得到你想要的那个?此代码将返回所有.jpg.jpeg文件。

Directory.GetFiles("Content/img/", ".jp?g"); 
+1

实际上,它会返回一个包含文件夹中每个文件的完整路径的字符串数组。 –

+0

理论上以下也是jpeg文件:.jpe,.jfif和.jif – Liz

+0

这只是告诉你他们是否有可能的扩展名。它不验证文件的格式。 –

1

如果你想知道是哪些文件具有JPEG扩展,我这样做:

HashSet<string> JpegExtensions = 
    new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) 
     { ".jpg", ".jpe", ".jpeg", ".jfi", ".jfif" }; // add others as necessary 

foreach(var fname in Directory.EnumerateFiles(pathname)) 
{ 
    if (JpegExtensions.Contains(Path.GetExtension(fname)) 
    { 
     Console.WriteLine(fname); // do something with the file 
    } 
} 
相关问题