使用Response.WriteFile给出访问被拒绝错误

时间:2014-12-19 10:39:31

标签: c# asp.net

我正在开发一个我在asp.net和c#中开发的网站。目前我的GridView有3列

  1. 文件名
  2. 文件说明
  3. 下载档案
  4. 我从数据库中获取所有3个值。这些值将以List的形式返回。除了下载文件选项之外,一切都按预期工作。我正在使用ASP:LinkButton以下

    <asp:LinkButton ID="lnkDownload" Text="Download" Font-Bold="true" CommandArgument='<%# Eval("FileLocation") %>' runat="server" OnClick="DownloadFile"></asp:LinkButton>
    

    完整的GridView代码是。

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="FileName" HeaderText="File Name" />
        <asp:BoundField DataField="FileDescription" HeaderText="Description" />
        <asp:TemplateField HeaderText="View Details">
            <ItemTemplate>
                <asp:LinkButton ID="lnkDownload" Text="Download" Font-Bold="true" CommandArgument='<%# Eval("FileLocation") %>' runat="server" OnClick="DownloadFile"></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    </asp:GridView>
    

    C#代码看起来像这样。

    protected void DownloadFile(object sender, EventArgs e)
    {
        string filePath = (sender as LinkButton).CommandArgument;
        Response.ContentType = ContentType;
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
        Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        Response.WriteFile(filePath);//This line is throwing the error
        Response.End();
    }
    

    我一直收到错误

    Access to the path 'My path' is denied. 
    

    该文件夹具有正确的权限。如果需要任何其他代码部分,请告诉我。在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您的问题可能是您尝试访问目录。

从MSDN doc获取有关getfilename方法的信息

string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string result;

result = Path.GetFileName(fileName);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    fileName, result);

result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    path, result);

// This code produces output similar to the following: 
// 
// GetFileName('C:\mydir\myfile.ext') returns 'myfile.ext' 
// GetFileName('C:\mydir\') returns ''

你确定你真的得到了文件名吗?或者只是目录,就像上面代码段中的第二个例子一样。

相关问题