我正在尝试向网站添加一项功能,该功能会将Outlook邀请附件发送到电子邮件。所有内容都是第一次完美运行,但在再次运行之后,我收到以下错误:“进程无法访问文件'OutlookCalendar.ics',因为它正被另一个进程使用。”我已经搜索了高和低的答案,但似乎当我使用file.WriteAllLines时,它不会关闭文件?请参阅下面的代码......
//CREATE OUTLOOK ATTACHMENT.....................................................................................................
//..............................................................................................................................
string schLocation = "Kettle Cuisine TBD";
string schSubject = visitor + " is visiting.";
string schDescription = other;
System.DateTime schBeginDate = Convert.ToDateTime(date + " " + time);
System.DateTime schEndDate = Convert.ToDateTime(date + " 17:00");
//PUTTING THE MEETING DETAILS INTO AN ARRAY OF STRING
String[] contents = { "BEGIN:VCALENDAR",
"PRODID:-//Flo Inc.//FloSoft//EN",
"BEGIN:VEVENT",
"DTSTART:" + schBeginDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"),
"DTEND:" + schEndDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"),
"LOCATION:" + schLocation,
"DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" + schDescription,
"SUMMARY:" + schSubject, "PRIORITY:3",
"END:VEVENT", "END:VCALENDAR" };
/*THE METHOD 'WriteAllLines' CREATES A FILE IN THE SPECIFIED PATH WITH
THE SPECIFIED NAME,WRITES THE ARRAY OF CONTENTS INTO THE FILE AND CLOSES THE
FILE.SUPPOSE THE FILE ALREADY EXISTS IN THE SPECIFIED LOCATION,THE CONTENTS
IN THE FILE ARE OVERWRITTEN*/
System.IO.File.WriteAllLines(Server.MapPath("OutlookCalendar.ics"), contents);
//END CREATE OUTLOOK ATTACHMENT.....................................................................................................
//..............................................................................................................................
//Send out email
Email.sendEmailOutlook(message, email, header);
在电子邮件部分我用这个.... //创建.ICS文件的附件
Attachment mailAttachment = new Attachment(System.Web.HttpContext.Current.Server.MapPath("OutlookCalendar.ics"));
mail.Attachments.Add(mailAttachment);
mail.IsBodyHtml = true;
//Set email message and subjet
mail.Subject = header;
mail.Body = message;
smtpClient.Send(mail);
答案 0 :(得分:4)
我怀疑问题不是File.WriteAllLines
,而是Attachment
- 实施IDisposable
,但是您没有处置它......所以如果它上面有一个打开的文件句柄,可以解释你所看到的内容。你可以使用:
var path = HttpContext.Current.Server.MapPath("OutlookCalendar.ics");
using (Attachment mailAttachment = new Attachment(path))
{
mail.Attachments.Add(mailAttachment);
mail.IsBodyHtml = true;
//Set email message and subjet
mail.Subject = header;
mail.Body = message;
smtpClient.Send(mail);
}
但是,根本不清楚为什么你需要写一个文件。最好将代码更改为只创建MemoryStream
。例如:
string text = string.Join("\r\n", contents);
byte[] encoded = Encoding.UTF8.GetBytes(text);
var stream = new MemoryStream(encoded);
using (var attachment = new Attachment(stream, "OutlookCalendar.ics"))
{
...
}
现在根本没有涉及任何文件,因此不存在任何冲突。