I want to have code that does the following:
foreach(File in Directory)
{
test to see if the file is a jpeg
}
but am unfamiliar with how to read from files. How do I do this?
I want to have code that does the following:
foreach(File in Directory)
{
test to see if the file is a jpeg
}
but am unfamiliar with how to read from files. How do I do this?
Why not use Directory.GetFiles()
to get only the ones you want? This code will return all .jpg
and .jpeg
files.
Directory.GetFiles("Content/img/", ".jp?g");
If you're targetting .NET 4 Directory.EnumerateFiles may be more efficient, especially for larger directories. If not, you can replace EnumerateFiles
with GetFiles
below.
//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();
Once you have a list of files with the correct extension, you can check if the file is actually a JPEG (as opposed to just being renamed .jpg
) by using on of the two different methods mentioned in this answer. (From that post)
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;
}
}
Or a more accurate, but slower, method
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;
}
}
If there's a chance that you have JPEG files that don't have the correct extension then you'll have to loop through all files within the directories (use *.*
as the filter) and perform one of the two methods above on them.
If all you want to know is which files have jpeg extensions, I would do this:
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
}
}