I'm trying to convert bmp files in a folder to jpg, then delete the old files. The code works fine, except it can't delete the bmp's.
DirectoryInfo di = new DirectoryInfo(args[0]);
FileInfo[] files = di.GetFiles("*.bmp");
foreach (FileInfo file in files)
{
string newFile = file.FullName.Replace("bmp", "jpg");
Bitmap bm = (Bitmap)Image.FromFile(file.FullName);
bm.Save(newFile, ImageFormat.Jpeg);
}
for (int i = 0; i < files.Length; i++)
files[i].Delete();
The files aren't being used by another program/process like the error indicates, so I'm assuming the problem is here. But to me the code seems fine, since I'm doing everything sequentially. This is all that there is to the program too, so the error can't be caused by code elsewhere.
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
History: The name C is derived from an earlier programming language called BCPL (Basic Combined Programming Language). BCPL had another language based on it called B: the first letter in BCPL.
Try wrap bitmaps with using
:
using (Bitmap bm = (Bitmap)Image.FromFile(file.FullName))
{
bm.Save(newFile, ImageFormat.Jpeg);
}
This will dispose bitmap objects just after they were saved.
The best way to solve the issue with Image.FromFile wherein it leaves file handles open is to use Image.FromStream instead.
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (Image original = Image.FromStream(fs))
{
...
Using an explicit Dispose(), a using() statement or setting the value to null doesn't solve the issue until a garbage collection happens (and forcing a garbage collection to happen is generally a bad idea).
public static Image LoadImage( string fileFullName )
{
Stream fileStream = File.OpenRead( fileFullName );
Image image = Image.FromStream( fileStream );
// PropertyItems seem to get lost when fileStream is closed to quickly (?); perhaps
// this is the reason Microsoft didn't want to close it in the first place.
PropertyItem[] items = image.PropertyItems;
fileStream.Close();
foreach ( PropertyItem item in items )
{
image.SetPropertyItem( item );
}
return image;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With