c# - 从 .NET Web 应用程序导出到 Outlook(.ics 文件)

标签 c# .net asp.net outlook icalendar

基本上,我正在尝试从 C# Web 应用程序创建和导出 .ics 文件,以便用户可以保存它,并在 Outlook 中打开它以向他们的日历添加内容。

这是我目前的代码...

string icsFile = createICSFile(description, startDate, endDate, summary);

//Get the paths required for writing the file to a temp destination on 
//the server. In the directory where the application runs from.

string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
string assPath = Path.GetDirectoryName(path).ToString();

string fileName = emplNo + "App.ics";
string fullPath = assPath.Substring(0, assPath.Length-4);

fullPath = fullPath + @"\VTData\Calendar_Event\UserICSFiles";

string writePath = fullPath + @"\" + fileName; //writepath is the path to the file itself.
//If the file already exists, delete it so a new one can be written.
if (File.Exists(writePath))
{
    File.Delete(writePath);
}
//Write the file.
using (System.IO.StreamWriter file = new System.IO.StreamWriter( writePath, true))
{
    file.WriteLine(icsFile);
}

以上内容完美无缺。它写入文件并首先删除所有旧文件。

我的主要问题是如何将它提供给用户?

我尝试将页面直接重定向到文件路径:

Response.Redirect(writePath);

它不起作用,并抛出以下错误:

htmlfile: Access is denied.

注意:如果我复制并粘贴 writePath 的内容,并将其粘贴到 Internet Explorer 中,则会打开保存文件对话框并允许我下载 .ics 文件。

我还尝试提示一个保存对话框来下载文件,

System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "inline; filename=" + fileName + ";");
response.TransmitFile(fullPath);
response.Flush(); // Error happens here
response.End();

也不行。

Access to the path 'C:\VT\VT-WEB MCSC\*some of path omitted *\VTData\Calendar_Event\UserICSFiles' is denied.

再次访问被拒绝错误。

可能是什么问题?

最佳答案

听起来您正试图为用户提供文件的物理路径而不是虚拟路径。尝试更改路径,使其以 www.yoursite.com/date.ics 格式结束。这将允许您的用户下载它。问题是他们无权访问您服务器上的 C 盘。

这里是如何执行此操作的链接:

http://www.west-wind.com/weblog/posts/2007/May/21/Downloading-a-File-with-a-Save-As-Dialog-in-ASPNET

基本上,您的代码中需要以下行:

Response.TransmitFile( Server.MapPath("~/VTData/Calendar_Event/UserICSFiles/App.ics") );

使用它代替 Response.Redirect(writePath);,你应该可以开始了。

关于c# - 从 .NET Web 应用程序导出到 Outlook(.ics 文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6204512/

相关文章:

c# - 使用参数转换数据类型 - ChangeType() 范围问题

c# - 有没有更好的方法来组合这两个 Linq 表达式?

c# - WinForms 中的进度条

c# - 查找所有 Func 委托(delegate)

c# - 未实现 INPC 的对象如何通知更改?

c# - 如何使用 INamingContainer 创建自定义控件?

c# - 扩展 C# .NET 应用程序 - 是否构建自定义脚本语言?

c# - 在长时间访问期间,隐藏字段是否比 session 更好地存储值

asp.net - 即使项目中没有错误,Xamarin 应用程序也不会部署

c# - 在 ASP .net WEB API 中使用属性路由进行版本控制