1

So I am making an outlook add-in where I the program reads emails attachments and saves them in the windows:(c) directory. But i want the program to delete email attachments from the directory after program finish's reading the attachments.

Code:

string path = @"C:\\att\\" + attachment.FileName;
attachment.SaveAsFIle(Path);
stuartd
  • 70,509
  • 14
  • 132
  • 163

2 Answers2

1

Not sure what your program structure looks like, but you can either: a) keep track of all the attachment files you're creating in the instance of the application or b) scan the attachments directory for the list of attachments you want to delete.

Then with this info you can just iterate over your list and delete the files using the System.IO.File class' Delete function:

foreach(var path in listOfAttachments)
{
   System.IO.File.Delete(path);
}
Overhed
  • 1,289
  • 1
  • 13
  • 41
  • Yes, the code you have provided worked. but it does have a problem. It does not delete the pdf files. Program throws an exception of 'System.IO.IOEXception' and the PMP.pdf is already running in a different program. – Qasim Iqbal Aug 03 '16 at 13:34
  • That is because your target file (PMP.pdf in this case), is locked due to being open by another program or a user. Obviously if a file is in use you won't be able to delete it. You need to figure out if this is due to your test environment or if it's a possible scenario in production. If it is, then I would skip over that file (try-catch surrounding your Delete call) and keep on iterating through the list. – Overhed Aug 03 '16 at 13:40
0

To delete a file: System.IO.File.Delete(path)

https://msdn.microsoft.com/en-us/library/system.io.file.delete(v=vs.110).aspx

You could iterate through the files inside the folder

https://msdn.microsoft.com/en-us/library/07wt70x2(v=vs.110).aspx

string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries)
{
        System.IO.File.Delete(fileName);
}
Diego
  • 786
  • 10
  • 22