【问题标题】:'System.IO.FileNotFoundException' when trying to save an outlook Attachment尝试保存 Outlook 附件时出现“System.IO.FileNotFoundException”
【发布时间】:2019-07-22 09:46:44
【问题描述】:

我已经构建了一个小型 Web 应用程序来读取 Outlook 日历中的约会,我使用了 Microsoft.Office.Interop.Outlook。现在我希望能够保存约会中的附件。

到目前为止,这是我的代码:

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);
    }
}

问题:

抛出异常:'System.IO.FileNotFoundException 恰好
附件.SaveAsFile(SavePath);

我已经到处看了,这个方法应该将附件保存到路径中,但它以某种方式试图读取文件。

【问题讨论】:

  • 目录D:\SaveTest\是否存在?
  • @mmathis 是的,我首先确定了这一点,现在检查我是否有写入权限
  • 不能通过服务(例如 IIS)使用 Office 应用(包括 Outlook)。

标签: c# outlook


【解决方案1】:

假设附件存在,FileNotFoundExecption 由路径中不存在的部分触发。你可以先检查路径是否存在:

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

然后你可以检查你是否对该目录有写权限:

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;
}

【讨论】:

  • 我很确定有写入权限,因为我已经尝试过 WriteallText 和其他一些写入和删除方法来检查我是否有权读取或写入,附件正在保存但随后被直接删除当我到达 Attachment.SaveAsFile(SavePath);编辑:错字
【解决方案2】:

你可以尝试做的 3 件事:

  1. 确保directory exists

  2. 检查 Attachment.FileName 是否具有有效的名称和扩展名

  3. 检查您的write access

【讨论】:

    【解决方案3】:

    System.IO.FileNotFoundExecption 意味着它找不到您要查找的文件或您尝试保存的路径。删除 @ 并尝试 "D:\foldername\" + attachment.filename。尽管删除 @ 应该仍然有效,但我认为您需要使用加号运算符。将帮助您发布整个代码块,以便我们了解从上到下发生的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-01
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      相关资源
      最近更新 更多