I have a program that
creates a directory (C:\\Temp) where image files are being saved. My form
closing event will clean up the image files, however it throws an exception..”The
process cannot access the file x.jpg because it is being used by another
process”..When I open the temp folder almost all of files saved there are
deleted except for one(x.jpg)..How can I stop the “another process” from
locking this file…
I used this code:
foreach
(string picturePath in
System.IO.Directory.GetFiles(“C:\\Temp”, "*.jpg"))
{
try
{
Process[]
myProcesses;
myProcesses = Process.GetProcessesByName("Outlook");
foreach
(Process myProcess in
myProcesses)
{
myProcess.CloseMainWindow();
}
FileStream
fs = File.Open(picturePath, FileMode.OpenOrCreate, FileAccess.Write,
FileShare.Delete);
File.Delete(picturePath);
fs.Close();
fs.Dispose();
}
Guingab MaricarPosted Aug 26, 2008, 11:58 PM
Nipun TomarPosted Aug 26, 2008, 3:57 AM
yes, in both cases. when you are saving the files as well as when deleting them. Hope this should help.
Guingab MaricarPosted Aug 26, 2008, 2:18 AM
try
{
...
...
File.Delete(picturePath);
}
finally
{
fs.Flush();
fs.Close();
fs.Dispose();
}
Nipun TomarPosted Aug 26, 2008, 12:31 AM