Im still getting exception file cant access its in use

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
The error is in the DorWork event and inside the part where is checking for Cancelltion:


<pre> if (bgw.CancellationPending == true)
{
e.Cancel = true;
gifImage.Dispose();
File.Delete(previewFileName);
makeGif = false;
foreach (FileInfo file in tempdir.GetFiles())
{
file.Delete();
}
break;
}[/code]
<br/>
The exception is on line: file.Delete();

For example: Access to the path 000047.Gif is denied.
The file.Delete(); is painted with green. And im doing 5 lines aboive it gifImage.Dispose(); but it dosent help.
The error happen when i click the RED X on the top right corner of the form while the program is working and its asking me if i want to close the form and stop the operation and click YES.

The full exception is:

Access to the path 000047.Gif is denied

System.UnauthorizedAccessException was unhandled by user code<br/>
Message=Access to the path 000047.Gif is denied.<br/>
Source=mscorlib<br/>
StackTrace:<br/>
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)<br/>
at System.IO.FileInfo.Delete()<br/>
at mws.Animation_Radar_Preview.backGroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in D:C-SharpDownload FileDownloading-File-Project-Version-012Downloading FileAnimation_Radar_Preview.cs:line 120<br/>
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)<br/>
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)<br/>
InnerException:

Im not sure why the files are access denied and how to release/dispose them ? I want that if i say YES and its quitting the form so it will delete this files since the user cancelled the operation.

The code:


<pre>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using unfreez_wrapper;
using DannyGeneral;

namespace mws
{
public partial class Animation_Radar_Preview : Form
{
bool makeGif;
Image gifImage;
DirectoryInfo tempdir;
private const int _blinkFrequency = 1000;
private const int _maxNumberOfBlinks = 5;
private int _blinkCount = 0;
FileInfo[] pngFileInfo;
FileInfo[] fi;
DirectoryInfo di;
private MemoryStream _memSt = null;
Image img;
int numberOfFiles;
string nameOfStartFile;
string nameOfEndFile;
List<string> Directories;
DirectoryInfo dir1;
string previewFileName;
string previewDirectory;
UnFreezWrapper unfreez;
String radar_images_download_directory;
String tempRadarPngToGifDirectory;
string path_exe;
int mtpStart;
int mtpEnd;

public Animation_Radar_Preview()
{
InitializeComponent();
button1.Enabled = true;
button2.Enabled = true;
makeGif = true;
timer1.Interval = _blinkFrequency;
radar_images_download_directory = Options_DB.Get_Radar_Images_Download_Directory();
path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
tempRadarPngToGifDirectory = Path.Combine(path_exe, "tempRadarPngToGifDirectory");
if (Directory.Exists(tempRadarPngToGifDirectory))
{
}
else
{
Directory.CreateDirectory(tempRadarPngToGifDirectory);
}
dir1 = new DirectoryInfo(tempRadarPngToGifDirectory);
if (gifImage != null)
{
gifImage.Dispose();
}
foreach (FileInfo file in dir1.GetFiles())
{
file.Delete();
}
Directories = new List<string>();
Directories.Add(radar_images_download_directory);
Directories.Add(tempRadarPngToGifDirectory);
backgroundWorker1.RunWorkerAsync(Directories);
mtpStart = Picturebox1_Fullscreen.mtp1Start;
mtpEnd = Picturebox1_Fullscreen.mtp1End;
unfreez = new UnFreezWrapper();
previewDirectory = path_exe + "\" + "previewDirectory";
if (Directory.Exists(previewDirectory))
{
}
else
{
Directory.CreateDirectory(previewDirectory);
}
previewFileName = previewDirectory + "\" + "preview.gif";
numberOfFiles = (mtpEnd - mtpStart)+1;
label2.Text = numberOfFiles.ToString();
di = new DirectoryInfo(radar_images_download_directory);
fi = di.GetFiles("*.png");
nameOfStartFile = fi[mtpStart].Name.ToString();
nameOfEndFile = fi[mtpEnd].Name.ToString();

label6.Text = nameOfStartFile.ToString();
label4.Text = nameOfEndFile.ToString();
backgroundWorker1.WorkerSupportsCancellation = true;
}

private void backGroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bgw = (BackgroundWorker)sender;
List<string> Directories = (List<string>)e.Argument;

String radar_images_download_directory = Directories[0];
String tempRadarPngToGifDirectory = Directories[1];
tempdir = new DirectoryInfo(tempRadarPngToGifDirectory);
List<string> myGifList = new List<string>();
dir1 = new DirectoryInfo(radar_images_download_directory);
pngFileInfo = dir1.GetFiles("*.png");
int total = pngFileInfo.Length;
int Counter = 0;
int percentage = 0;
for (int i = mtpStart; i < mtpEnd; i++)//for (int i = mtpStart; i< mtpEnd;i++)//foreach (FileInfo SingleFileInfo in pngFileInfo)
{
if (bgw.CancellationPending == true)
{
e.Cancel = true;
gifImage.Dispose();
File.Delete(previewFileName);
makeGif = false;
foreach (FileInfo file in tempdir.GetFiles())
{
file.Delete();
}
break;
}
else
{
try
{
String FileName = tempRadarPngToGifDirectory + "\" + Counter.ToString("D6") + ".Gif";

// loading png and convert it to gif
gifImage = Image.FromFile(pngFileInfo.FullName);
gifImage.Save(FileName, System.Drawing.Imaging.ImageFormat.Gif);
gifImage.Dispose();
Counter += 1;
// add the filename to the List
myGifList.Add(FileName);
// calculating percentage and report it
percentage = Counter * 100 / total;//(total / 100) * Counter;
bgw.ReportProgress(percentage);

}
catch (Exception ex)
{
// this is a bad idea inside a backgroundworker
MessageBox.Show("error >>>>>> " + ex);
}
}


}
numberOfFiles = myGifList.Count();
if (makeGif == false)
{
}
else
{
unfreez.MakeGIF(myGifList, previewFileName, 8, true);
}
bgw.ReportProgress(100);
// whatever this will do

//unfreez.MakeGIF(myGifList, previewFileName, animatedGifSpeed, loop);

// setting the myGifList as the result of the method
e.Result = myGifList;

}
private void backGroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar2.Value = e.ProgressPercentage;
}

List<string> myGifList;
private void backGroundWorker1_Completed(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
label7.Visible = true;
label7.ForeColor = Color.Red;
label7.Text = "Operation Has Been Cancelled";
button2.Enabled = false;
}

else if (!(e.Error == null))
{

}

else
{
myGifList = (List<string>)e.Result;
pictureBoxImage(previewFileName);
timer1.Stop();
label7.Visible = true;
label7.ForeColor = Color.Green;
label7.Text = "Operation Have Been Completed";
button1.Enabled = false;
progressBar2.EndColor = Color.FromArgb(0, 211, 040);
}
}

public static bool IsDirectoryEmpty(DirectoryInfo directory)
{
FileInfo[] files = directory.GetFiles();
DirectoryInfo[] subdirs = directory.GetDirectories();

return (files.Length == 0 && subdirs.Length == 0);
}

private void button2_Click(object sender, EventArgs e)
{
DialogResult result1;
result1 = new DialogResult();
SaveFileDialog sd = new SaveFileDialog();
sd.Title = "Select a folder to save the animated gif to";
sd.InitialDirectory = "c:\";
sd.FileName = null;
sd.Filter = "Gif File|*.gif;*.jpg|Gif|*.gif";
sd.FilterIndex = 1;
sd.RestoreDirectory = true;
result1 = sd.ShowDialog();
string file1 = sd.FileName;
if (result1 == DialogResult.OK)
{
File.Move(previewFileName, file1);
}
}

private void button1_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
// Cancel the asynchronous operation.
progressBar2.EndColor = Color.FromArgb(210, 0, 0);
label7.ForeColor = Color.Red;
label7.Text = "Operation Has Been Cancelled";
timer1.Stop();
backgroundWorker1.CancelAsync();
}

}


public void pictureBoxImage(string pbImage)
{
Image img2 = null;
try
{
using (img = Image.FromFile(pbImage))
{
//get the old image thats loaded from the _memSt memorystream
//and dispose it
Image i = this.pictureBox1.Image;
this.pictureBox1.Image = null;

if (i != null)
i.Dispose();

//grab the old stream
MemoryStream m = _memSt;

//save the new image to this stream
_memSt = new MemoryStream();
img.Save(_memSt, System.Drawing.Imaging.ImageFormat.Gif);

if (m != null)
m.Dispose();

//create our image to display
img2 = Image.FromStream(_memSt);
}

if (img2 != null)
pictureBox1.Image = img2;
label2.Text = numberOfFiles.ToString();
label6.Text = nameOfStartFile.ToString();
label4.Text = nameOfEndFile.ToString();
//File.Delete(pbImage);
}
catch (Exception err)
{
Logger.Write("Animation Error >>> " + err);
}
}

private void timer1_Tick(object sender, EventArgs e)
{
this.label7.Visible = !this.label7.Visible;
_blinkCount++;

}

private void Animation_Radar_Preview_FormClosing(object sender, FormClosingEventArgs e)
{
if (progressBar2.EndColor == Color.FromArgb(210, 0, 0))
{
}
else
{
DialogResult dlg = MessageBox.Show("Are you sure you want to exit and cancel the operation ?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

if (dlg == DialogResult.Yes)
{
backgroundWorker1.CancelAsync();
if (gifImage != null)
{
gifImage.Dispose();
}
dir1 = new DirectoryInfo(tempRadarPngToGifDirectory);
foreach (FileInfo file in dir1.GetFiles())
{
file.Delete();
}
File.Delete(previewFileName);
//maybe more code
}
else if (dlg == DialogResult.No)
{
e.Cancel = true;
return;
}
}
//more code
//...

}
}
}[/code]

I did in the code that if the work completed and you try to quit without saving/create first the animated file it will cancel also and should delete also the files.
I also did that if i click the cancel button and quit the form it will not ask anything the cancel button already delete all the temp files.

The problem is with this part when trying to close the form in the middle of the work.

Thanks. <hr class="sig danieli

View the full article
 
Back
Top