In my current project I’m facing random errors complaining the file in question is being used by other processes.
Sometime it acts fast and everything is just fine, some other times it won’t work and keeps giving me the error
The file is being used by another process
So I thought I place the delete method inside a try-catch and in the catch I have some kind of loop which would try to delete the file or even better: unlocks it and makes it ready for being deleted.
I have no idea if inside that loop I get another exception, and how to manage that. How can I find a solution to detach that process from the file, and make it ready for deletion?
Update
This is my code at the moment:
private void Test(string imagePath)
{
try
{
if (File.Exists(imagePath))
{
pictureBoxExistingPicture.Visible = true;
labelnew.Visible = true;
labelold.Visible = true;
pictureBoxExistingPicture.Image = ImageUtility.SafeLoadImage(imagePath);
if (MessageBox.Show("Do you want to overwrite the existing image?", "warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
{
pictureBoxExistingPicture.Image = Properties.Resources._default;//restore default
while (true)
{
try
{
File.Delete(imagePath);
break;
}
catch (Exception)
{
}
}
pictureBoxHonarjo.Image.Save(imagePath);
}
else
{
pictureBoxHonarjo.Image = ImageUtility.SafeLoadImage(imagePath);//restore original image
}
pictureBoxExistingPicture.Visible = false;
labelnew.Visible = false;
labelold.Visible = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
in the current context of the subject, i need to say that if the user wishes to replace the image, it should get done , and it shouldn’t take a long time nor should it fail to do so.So basically when someone tries to change a picture,It must get changed in a fraction of the time.
And for the SafeLoadImage function, here is my implementation:
public class ImageUtility
{
public static byte[] ImageToBytes(string FilePath, int FileLength)
{
FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
BinaryReader breader = new BinaryReader(fileStream);
return breader.ReadBytes(FileLength);
}
public static Image SafeLoadImage(string imagePath)
{
byte[] image_byte;
Image image;
FileInfo fileinfo = new FileInfo(imagePath);
image_byte = ImageUtility.ImageToBytes(imagePath, (int)fileinfo.Length);
image = ImageUtility.BytesToImage(image_byte);
return image;
}
}
ImageUtility.ImageToBytesdoesn’t dispose the FileStream when finishedCould it be this that’s locking the file?
Consider the
usingstatement which will free resources after execution exits the code block (it wraps IDisposable and calls the dispose method for you):This may be the reason your file is locked.
Of course if someone else is locking your file, then this might be useless 🙂 but I suspect that these are image files you have created/are processing