My winform application periodically pulls a flash file from an SQL database, writes it to a temporary folder, displays it in a webbroswer control, and then deletes it from the temporary folder. My application creates the temporary folder if it does not exist. The temporary folder is located in 'System.Environment.CurrentDirectory'.
My problem is the permissions of the temporary folder frequently become read only and then my application cannot delete the file. Sometimes the problem occurs immediately, and sometimes I can run the application several times before it occurs.
How do I insure that the file is deleted?
I added code to delete the temporary folder and then re-create it each time it writes to it, but this did not resolve my problem.
Only my application needs to access this folder, and the folder only holds these flash images.
I thought about using the generic 'temp' folder, but read somewhere that that could lead to problems.
Also, I got the same problem when I located the temporary folder at 'D:\'.
I'm using VS2008 on Windows XP. The application is to run on XP, Vista and 7.
Here is code.
DataSet dsFlashQuizRandom = new DataSet();
dsFlashQuizRandom = objUserDAO.GetFlashQuizRandom(intAge);
if (dsFlashQuizRandom.Tables[0].Rows[0]["large_image_blob"] != null && dsFlashQuizRandom.Tables[0].Rows[0]["file_name"].ToString().Trim() != string.Empty)
{
byte[] b = (byte[])dsFlashQuizRandom.Tables[0].Rows[0]["large_image_blob"];
if (b != null)
{
string flashFileName = dsFlashQuizRandom.Tables[0].Rows[0]["file_name"].ToString().Trim();
string targetPath = System.Environment.CurrentDirectory.ToString() + @"\images\";
string strFileName = targetPath + flashFileName;
//Delete the current version of the folder (if it exists); then create a new version of it.
if (System.IO.Directory.Exists(targetPath))
System.IO.Directory.Delete(targetPath, true);
if (!System.IO.Directory.Exists(targetPath))
System.IO.Directory.CreateDirectory(targetPath);
//Write the file to a FileStream, assign that stream to the webbrowser control.
FileStream fs = new FileStream(strFileName, FileMode.CreateNew, FileAccess.Write);
fs.Write(b, 0, b.Length);
fs.Close();
webBrowserQuizFlash.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowserQuizFlash_DocumentCompleted);
webBrowserQuizFlash.Url = new System.Uri(strFileName, System.UriKind.Absolute);
}
}
//Delete the Flash Webbrowser file once it has completed loading.
private void webBrowserQuizFlash_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
FileInfo fi = new FileInfo(strFileName);
try
{
fi.Delete();
}
catch (IOException ex)
{
MessageBox.Show("IOException = " + ex); //test code
}
}
Any suggestions or a point in the right direction would be appreciated.
Cheers, Frederick
PS--When copying my code to this post I see the color of the text is all red after the @"\images\"; Is there a problem with this part of my code, or is this a display artifact? Should I use this instead: @"\images\\";