0

I have built a small web application to read appointments from outlook calendar and i used Microsoft.Office.Interop.Outlook. Now I want to to able to save the attachments which are inside the appointment.

Here is my code so far :

foreach (var item in AppointmentItems) {    
    for (int i = 1; i <= item.Attachments.Count; i++) {

        var Attachment = item.Attachments[i];

        string SavePath = Path.Combine(@"D:\SaveTest", Attachment.FileName);

        Attachment.SaveAsFile(SavePath);
    }
}

Problem :

Exception thrown: 'System.IO.FileNotFoundException at exactly
Attachment.SaveAsFile(SavePath);

I have already looked everywhere, this method should save the attachment to the path but its somehow trying to read a file.

Giulio Caccin
  • 2,962
  • 6
  • 36
  • 57

3 Answers3

3

Assuming that the attachment exist, FileNotFoundExecption is triggered by a not existing part of your path. You can check if the path exist first:

Directory.Exists(@"D:\SaveTest")

Then you can check if you have write rights on the directory:

Try
{
return System.IO.Directory.GetAccessControl(@"D:\SaveTest")
        .GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount))
        .Cast<System.Security.AccessControl.FileSystemAccessRule>()
        .Where(rule => (System.Security.AccessControl.FileSystemRights.Write & rule.FileSystemRights) == System.Security.AccessControl.FileSystemRights.Write)
        .Any(rule => rule.AccessControlType == System.Security.AccessControl.AccessControlType.Allow);
} catch(Exception)
{
  return false;
}
Giulio Caccin
  • 2,962
  • 6
  • 36
  • 57
  • i am pretty sure writing rights are there because i have tried WriteallText and some other writing and deleting methods to check if i have rights to read or write , the thing the attachment is being saved but then directly deleted as i reach the line Attachment.SaveAsFile(SavePath); Edit : typo – PassionateCoder Jul 22 '19 at 14:19
  • Can you take a look at this https://stackoverflow.com/questions/31072981/saving-device-independent-bitmap-attachment ? – Giulio Caccin Jul 22 '19 at 15:09
1

3 things you could try to do:

  1. Make sure that the directory exists

  2. Check if Attachment.FileName have valid name and extension

  3. Check your write access

AdlerCode
  • 11
  • 2
0

System.IO.FileNotFoundExecption means it can't find the file you are looking for or the path you are trying to save to in your case. remove @ and try "D:\foldername\" + attachment.filename. although removing @ should still work I think you need use plus operator. Would help you can post the whole block of code so we can understand what is going on from top to bottom.

Waheed Rafiq
  • 460
  • 1
  • 6
  • 17