none
How to force delete a directory/file?

    Question

  • Hi All,

    I wanted to delete directory/file forcefully from my c# application. The problem is when I try to delete a file, which i created earlier from the same application, I got an error that the file cannot be access as it is used by another process. Is there any way to overcome this issue. Need help in sample, demo, example.

    Thanks
    SN Zeih ZeZen
    Monday, April 20, 2009 7:23 AM

Answers

  • Hi,

    So, are you creating a file through your application in one Step and then trying to delete the same file after some Steps?
    If so, are you sure- you are not leaving the previously created file - OPEN or UNDER-USAGE by the Application?

    If you have created the file, please double check if you are closing the file before deleting it.

    For example, if you created an Excel File, pelase check if you have closed the file, as :

                    MSExcel.ApplicationClass msExcel = new MSExcel.ApplicationClass();

                    MSExcel._Workbook msExcelWorkbook = <-- Your Excel File - that has been craeted or opened -->

                                         --- some code here ----

                    msExcelWorkbook.SaveAs(excelFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                           Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
                                           Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                    msExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);

                    msExcel.Quit();


    Regards, Lakra :)
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:28 AM
    Monday, April 20, 2009 8:53 AM
  • Dear friends,

    Sorry for not mentioning the problem in details. Here is the details of the problem i faced.

    The file which i create is an image file (.jpg). it is created from a powerpoint slide using the export(...) method, i opened powerpoint slide show within my windows application and run the show in a winform. after creating this file i used for displaying on the form as a thumbnail. Assume that my application is opening and running a slide show. now a situation arise that when I try to open the second powerpoint slide show within my application, i have to update the thumbnails, this process requires me to delete or overwrite the existing image file. I try the first option of deleting and recreating with the new image file at this point of time i have the delete problem. even if i try to overwrite it will give the same error i guess.

    Need your helps,


    Thanks
    SN Zeih ZeZen
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:28 AM
    Monday, April 20, 2009 9:14 AM
  • It is your code that creates the lock on the file.  You'll have to call the Dispose() method first to release the lock.  Something like:

      pictureBox1.Image.Dispose();
      pictureBox1.Image = null;
      // Now it's okay to create a new thumbnail with the same file name
      //...
    Hans Passant.
    • Proposed as answer by Kira Qian Wednesday, April 22, 2009 3:20 AM
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:28 AM
    Monday, April 20, 2009 10:22 AM
  • I got your suggestion and i do implement, but i got an error when i open one after the other. i got index out of range or sometimes when the previous have more slide than the one i open currently it says slide10.jpg is not accessible......

    My code as below:
    if (pptPresenation.Slides.Count > 0)
    {
    	try
    	{
    		if (tabLeftNav.TabPages[1].Controls.Count > 0)
    		{
    			foreach(PictureBox ctl in tabLeftNav.TabPages[1].Controls)
    			{
    				try
    				{
    					if (ctl != null)
    					{
    						KillImages(ctl);
    					}
    				}
    				catch { }
    			}
    		}
    		tabLeftNav.TabPages[1].Controls.Clear();
    		if (Directory.Exists(@"d:\myslides"))
    		{
    			Directory.Delete(@"d:\myslides", true);
    		}
    		Directory.CreateDirectory(@"d:\myslides");
    	}
    	catch (Exception ex) { MessageBox.Show(ex.Message); }
    }
    
    
    
    
    
    private void KillImages(PictureBox pBox)
    {
    	pBox.ImageLocation = "";
    	pBox.Image.Dispose();
    	pBox.Image = null;
    	pBox.Dispose();
    	pBox = null;
    }

    Need some more help. Thanks

    SN Zeih ZeZen
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:27 AM
    Wednesday, April 22, 2009 4:47 AM
  • Don't hide exceptions with empty catch clauses.  Don't change the properties of the PictureBox before disposing the image.  Clean up *before* you load new slides.
    Hans Passant.
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:27 AM
    Wednesday, April 22, 2009 4:55 AM
  • Post your code of part that loads images into Picture boxes..that would be helpful.
    Prakash Subramani (MCAD)
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:27 AM
    Wednesday, April 22, 2009 4:56 AM
  • Following is code for generating images and loading into picture box

    //Code to export to image (.jpg) file
    private void CreateThumbnails(PowerPoint._Slide sld)
    {
    	string filePath_Name = @"d:\myslides\slide" + sld.SlideNumber + ".jpg";
    	string graphictype = "jpg";
    	int scalewidth = tabLeftNav.TabPages[1].Width - 20;
    	int scaleheight = tabLeftNav.TabPages[1].Width - 100;
    	sld.Export(filePath_Name, graphictype, scalewidth, scaleheight);
    }
    
    
    //Code to load images (.jpg) to picturebox
    private void ShowThumbnails()
    {
    	int buttonTop = 2;
    	foreach (PowerPoint._Slide slide in pptPresenation.Slides)
    	{
    		string filePath_Name = @"d:\myslides\slide" + slide.SlideNumber + ".jpg";
    		PictureBox imgButton = new PictureBox();
    		imgButton.Cursor = Cursors.Hand;
    		imgButton.Name = slide.Name + "-" + slide.SlideNumber;
    		imgButton.Image = Image.FromFile(filePath_Name);
    		imgButton.Width = tabLeftNav.TabPages[1].Width - 20;
    		imgButton.Height = tabLeftNav.TabPages[1].Width - 100;
    		imgButton.Left = 2;
                    imgButton.Top = buttonTop;
    		buttonTop = buttonTop + (imgButton.Height + 5);
    		imgButton.Click += new EventHandler(imgButton_Click);
    				tabLeftNav.TabPages[1].Controls.Add(imgButton);
    	}
    }
    
    
    ////
    private void ShowInsideWindow(string fileName)
    {
    	try
    	{
    		//open powerpoint presentation file
    		pptPresenation = this.pptApplication.Presentations.Open(fileName, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse);
    		if (pptPresenation.Slides.Count > 0)
    		{
    			try
    			{
    				if (tabLeftNav.TabPages[1].Controls.Count > 0)
    				{
    					foreach(PictureBox ctl in tabLeftNav.TabPages[1].Controls)
    					{
    						try
    						{
    							if (ctl != null)
    							{
    								KillImages(ctl);
    			tabLeftNav.TabPages[1].Controls.Remove(ctl);
    							}
    						}
    						catch { }
    					}
    				}
    				if (Directory.Exists(@"d:\myslides"))
    				{
    					Directory.Delete(@"d:\myslides", true);
    				}
    				Directory.CreateDirectory(@"d:\myslides");
    			}
    			catch (Exception ex) { MessageBox.Show(ex.Message); }
    
    			//if total number of slide is more than zero
    			//then prepare to run slide show
    			try
    			{
    				int buttonTop = 2;
    				tabLeftNav.TabPages[0].Controls.Clear();
    				List<string> titles = PPTGetSlideTitles(fileName);
    				foreach (PowerPoint._Slide slide in pptPresenation.Slides)
    				{
    					Button btnNav = new Button();
    					btnNav.TextAlign = ContentAlignment.MiddleLeft;
    					btnNav.AutoEllipsis = true;
    					btnNav.FlatStyle = FlatStyle.Flat;
    					btnNav.Cursor = Cursors.Hand;
    					btnNav.Name = slide.Name + "-" + slide.SlideNumber;
    					btnNav.Text = titles[slide.SlideNumber - 1];
    					toolTip1.SetToolTip(btnNav, titles[slide.SlideNumber - 1]);
    					btnNav.Width = tabLeftNav.TabPages[0].Width - 20;
    					btnNav.Left = 2;
    					btnNav.Top = buttonTop;
    					buttonTop = buttonTop + (btnNav.Height + 3);
    					btnNav.Click += new EventHandler(btnNav_Click);
    							tabLeftNav.TabPages[0].Controls.Add(btnNav);
    				        ///call to create thumbnail
    					CreateThumbnails(slide);
    				}
    			}
    			catch { }
    			float fw = this.panContainer.Width - 179;
    			float fh = 415;
    			pptPresenation.SlideShowSettings.Run().Height = fh;
    			pptPresenation.SlideShowSettings.Run().Width = fw;
    	SetParent(pptPresenation.SlideShowSettings.Run().HWND, (int)this.panContainer.Handle);
    				}
    				else
    				{
    					//alert to user
    					MessageBox.Show("There is no slide in this Presentation.", "No Slides", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    				}
    			}
    			catch (Exception ex) 
    			{
    				if (ex.Message.ToLower().Contains("failed"))
    				{
    					if (MessageBox.Show("PowerPoint 2007 did not exit properly in the earlier session. Do you want to terminate now?", "Terminate PowerPoint 2007", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    					{
    						foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName("POWERPNT"))
    						{
    							if (p.HasExited == false)
    								p.Kill();
    						}
    					}
    				}
    				else
    				{
    					MessageBox.Show(ex.Message);
    				}
    			}
    		}


    private void btnOpen_Click(object sender, EventArgs e)
    		{
    			OpenFileDialog open = new OpenFileDialog();
    			open.AddExtension = true;
    			open.DefaultExt = "pptx";
    			open.RestoreDirectory = true;
    			open.Filter = "Presentation (*.pptx,*.ppt)|*.pptx;*.ppt";
    			if (open.ShowDialog() == DialogResult.OK)
    			{
    				try
    				{
    					if (pptPresenation != null)
    					{
    						pptPresenation.Close();
    						pptPresenation = null;
    					}
    				}
    				catch { pptPresenation = null; }
    				if (Path.GetExtension(open.FileName) == ".pptx")
    				{
    
    					try
    					{
    						ShowInsideWindow(open.FileName);
    						lblTotalSlides.Text = "Total Slides: " + pptPresenation.Slides.Count;
    						lblElapseTime.Text = pptPresenation.SlideShowSettings.Run().View.PresentationElapsedTime.ToString();
    						lblTitle.Text = Path.GetFileNameWithoutExtension(open.FileName);
    						ShowThumbnails();
    					}
    					catch { }
    				}
    				else
    				{
    					MessageBox.Show("Currently viewer supports only PowerPoint 2007.", "Unknown File Format", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    				}
    			}
    		}

    SN Zeih ZeZen
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:27 AM
    Wednesday, April 22, 2009 5:14 AM
  • OK. as nobugz said, disposing the image object will release the file handle to delete it is the way to delete the file. try to figure out the index problem.
    Prakash Subramani (MCAD)
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:27 AM
    Wednesday, April 22, 2009 5:39 AM
  • Thanks guys for your quick responses. I will try finding another way of accomplicing the task on the index problem.

    Thanks once again


    SN Zeih ZeZen
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:27 AM
    Wednesday, April 22, 2009 8:27 AM

All replies

  • Hi,

    So, are you creating a file through your application in one Step and then trying to delete the same file after some Steps?
    If so, are you sure- you are not leaving the previously created file - OPEN or UNDER-USAGE by the Application?

    If you have created the file, please double check if you are closing the file before deleting it.

    For example, if you created an Excel File, pelase check if you have closed the file, as :

                    MSExcel.ApplicationClass msExcel = new MSExcel.ApplicationClass();

                    MSExcel._Workbook msExcelWorkbook = <-- Your Excel File - that has been craeted or opened -->

                                         --- some code here ----

                    msExcelWorkbook.SaveAs(excelFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                           Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
                                           Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                    msExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);

                    msExcel.Quit();


    Regards, Lakra :)
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:28 AM
    Monday, April 20, 2009 8:53 AM
  • Dear friends,

    Sorry for not mentioning the problem in details. Here is the details of the problem i faced.

    The file which i create is an image file (.jpg). it is created from a powerpoint slide using the export(...) method, i opened powerpoint slide show within my windows application and run the show in a winform. after creating this file i used for displaying on the form as a thumbnail. Assume that my application is opening and running a slide show. now a situation arise that when I try to open the second powerpoint slide show within my application, i have to update the thumbnails, this process requires me to delete or overwrite the existing image file. I try the first option of deleting and recreating with the new image file at this point of time i have the delete problem. even if i try to overwrite it will give the same error i guess.

    Need your helps,


    Thanks
    SN Zeih ZeZen
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:28 AM
    Monday, April 20, 2009 9:14 AM
  • It is your code that creates the lock on the file.  You'll have to call the Dispose() method first to release the lock.  Something like:

      pictureBox1.Image.Dispose();
      pictureBox1.Image = null;
      // Now it's okay to create a new thumbnail with the same file name
      //...
    Hans Passant.
    • Proposed as answer by Kira Qian Wednesday, April 22, 2009 3:20 AM
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:28 AM
    Monday, April 20, 2009 10:22 AM
  • I got your suggestion and i do implement, but i got an error when i open one after the other. i got index out of range or sometimes when the previous have more slide than the one i open currently it says slide10.jpg is not accessible......

    My code as below:
    if (pptPresenation.Slides.Count > 0)
    {
    	try
    	{
    		if (tabLeftNav.TabPages[1].Controls.Count > 0)
    		{
    			foreach(PictureBox ctl in tabLeftNav.TabPages[1].Controls)
    			{
    				try
    				{
    					if (ctl != null)
    					{
    						KillImages(ctl);
    					}
    				}
    				catch { }
    			}
    		}
    		tabLeftNav.TabPages[1].Controls.Clear();
    		if (Directory.Exists(@"d:\myslides"))
    		{
    			Directory.Delete(@"d:\myslides", true);
    		}
    		Directory.CreateDirectory(@"d:\myslides");
    	}
    	catch (Exception ex) { MessageBox.Show(ex.Message); }
    }
    
    
    
    
    
    private void KillImages(PictureBox pBox)
    {
    	pBox.ImageLocation = "";
    	pBox.Image.Dispose();
    	pBox.Image = null;
    	pBox.Dispose();
    	pBox = null;
    }

    Need some more help. Thanks

    SN Zeih ZeZen
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:27 AM
    Wednesday, April 22, 2009 4:47 AM
  • Don't hide exceptions with empty catch clauses.  Don't change the properties of the PictureBox before disposing the image.  Clean up *before* you load new slides.
    Hans Passant.
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:27 AM
    Wednesday, April 22, 2009 4:55 AM
  • Post your code of part that loads images into Picture boxes..that would be helpful.
    Prakash Subramani (MCAD)
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:27 AM
    Wednesday, April 22, 2009 4:56 AM
  • Following is code for generating images and loading into picture box

    //Code to export to image (.jpg) file
    private void CreateThumbnails(PowerPoint._Slide sld)
    {
    	string filePath_Name = @"d:\myslides\slide" + sld.SlideNumber + ".jpg";
    	string graphictype = "jpg";
    	int scalewidth = tabLeftNav.TabPages[1].Width - 20;
    	int scaleheight = tabLeftNav.TabPages[1].Width - 100;
    	sld.Export(filePath_Name, graphictype, scalewidth, scaleheight);
    }
    
    
    //Code to load images (.jpg) to picturebox
    private void ShowThumbnails()
    {
    	int buttonTop = 2;
    	foreach (PowerPoint._Slide slide in pptPresenation.Slides)
    	{
    		string filePath_Name = @"d:\myslides\slide" + slide.SlideNumber + ".jpg";
    		PictureBox imgButton = new PictureBox();
    		imgButton.Cursor = Cursors.Hand;
    		imgButton.Name = slide.Name + "-" + slide.SlideNumber;
    		imgButton.Image = Image.FromFile(filePath_Name);
    		imgButton.Width = tabLeftNav.TabPages[1].Width - 20;
    		imgButton.Height = tabLeftNav.TabPages[1].Width - 100;
    		imgButton.Left = 2;
                    imgButton.Top = buttonTop;
    		buttonTop = buttonTop + (imgButton.Height + 5);
    		imgButton.Click += new EventHandler(imgButton_Click);
    				tabLeftNav.TabPages[1].Controls.Add(imgButton);
    	}
    }
    
    
    ////
    private void ShowInsideWindow(string fileName)
    {
    	try
    	{
    		//open powerpoint presentation file
    		pptPresenation = this.pptApplication.Presentations.Open(fileName, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse);
    		if (pptPresenation.Slides.Count > 0)
    		{
    			try
    			{
    				if (tabLeftNav.TabPages[1].Controls.Count > 0)
    				{
    					foreach(PictureBox ctl in tabLeftNav.TabPages[1].Controls)
    					{
    						try
    						{
    							if (ctl != null)
    							{
    								KillImages(ctl);
    			tabLeftNav.TabPages[1].Controls.Remove(ctl);
    							}
    						}
    						catch { }
    					}
    				}
    				if (Directory.Exists(@"d:\myslides"))
    				{
    					Directory.Delete(@"d:\myslides", true);
    				}
    				Directory.CreateDirectory(@"d:\myslides");
    			}
    			catch (Exception ex) { MessageBox.Show(ex.Message); }
    
    			//if total number of slide is more than zero
    			//then prepare to run slide show
    			try
    			{
    				int buttonTop = 2;
    				tabLeftNav.TabPages[0].Controls.Clear();
    				List<string> titles = PPTGetSlideTitles(fileName);
    				foreach (PowerPoint._Slide slide in pptPresenation.Slides)
    				{
    					Button btnNav = new Button();
    					btnNav.TextAlign = ContentAlignment.MiddleLeft;
    					btnNav.AutoEllipsis = true;
    					btnNav.FlatStyle = FlatStyle.Flat;
    					btnNav.Cursor = Cursors.Hand;
    					btnNav.Name = slide.Name + "-" + slide.SlideNumber;
    					btnNav.Text = titles[slide.SlideNumber - 1];
    					toolTip1.SetToolTip(btnNav, titles[slide.SlideNumber - 1]);
    					btnNav.Width = tabLeftNav.TabPages[0].Width - 20;
    					btnNav.Left = 2;
    					btnNav.Top = buttonTop;
    					buttonTop = buttonTop + (btnNav.Height + 3);
    					btnNav.Click += new EventHandler(btnNav_Click);
    							tabLeftNav.TabPages[0].Controls.Add(btnNav);
    				        ///call to create thumbnail
    					CreateThumbnails(slide);
    				}
    			}
    			catch { }
    			float fw = this.panContainer.Width - 179;
    			float fh = 415;
    			pptPresenation.SlideShowSettings.Run().Height = fh;
    			pptPresenation.SlideShowSettings.Run().Width = fw;
    	SetParent(pptPresenation.SlideShowSettings.Run().HWND, (int)this.panContainer.Handle);
    				}
    				else
    				{
    					//alert to user
    					MessageBox.Show("There is no slide in this Presentation.", "No Slides", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    				}
    			}
    			catch (Exception ex) 
    			{
    				if (ex.Message.ToLower().Contains("failed"))
    				{
    					if (MessageBox.Show("PowerPoint 2007 did not exit properly in the earlier session. Do you want to terminate now?", "Terminate PowerPoint 2007", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    					{
    						foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName("POWERPNT"))
    						{
    							if (p.HasExited == false)
    								p.Kill();
    						}
    					}
    				}
    				else
    				{
    					MessageBox.Show(ex.Message);
    				}
    			}
    		}


    private void btnOpen_Click(object sender, EventArgs e)
    		{
    			OpenFileDialog open = new OpenFileDialog();
    			open.AddExtension = true;
    			open.DefaultExt = "pptx";
    			open.RestoreDirectory = true;
    			open.Filter = "Presentation (*.pptx,*.ppt)|*.pptx;*.ppt";
    			if (open.ShowDialog() == DialogResult.OK)
    			{
    				try
    				{
    					if (pptPresenation != null)
    					{
    						pptPresenation.Close();
    						pptPresenation = null;
    					}
    				}
    				catch { pptPresenation = null; }
    				if (Path.GetExtension(open.FileName) == ".pptx")
    				{
    
    					try
    					{
    						ShowInsideWindow(open.FileName);
    						lblTotalSlides.Text = "Total Slides: " + pptPresenation.Slides.Count;
    						lblElapseTime.Text = pptPresenation.SlideShowSettings.Run().View.PresentationElapsedTime.ToString();
    						lblTitle.Text = Path.GetFileNameWithoutExtension(open.FileName);
    						ShowThumbnails();
    					}
    					catch { }
    				}
    				else
    				{
    					MessageBox.Show("Currently viewer supports only PowerPoint 2007.", "Unknown File Format", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    				}
    			}
    		}

    SN Zeih ZeZen
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:27 AM
    Wednesday, April 22, 2009 5:14 AM
  • OK. as nobugz said, disposing the image object will release the file handle to delete it is the way to delete the file. try to figure out the index problem.
    Prakash Subramani (MCAD)
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:27 AM
    Wednesday, April 22, 2009 5:39 AM
  • Thanks guys for your quick responses. I will try finding another way of accomplicing the task on the index problem.

    Thanks once again


    SN Zeih ZeZen
    • Marked as answer by SN Ngaihte Wednesday, April 22, 2009 8:27 AM
    Wednesday, April 22, 2009 8:27 AM