2014-12-19 36 views
0

我正在開發一個網站,我正在開發asp.net和c#。目前,我有這有3列使用Response.WriteFile提供訪問被拒絕錯誤

一個 GridView
  1. 文件名
  2. 文件描述
  3. 下載文件

我從數據庫中獲取所有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. 

文件夾具有正確的權限。如果需要其他代碼部分,請告訴我。在此先感謝您的幫助。

+0

@CodeCaster在我將它作爲'List'返回之前,它正在工作:/我已將IIS_IUSER組添加到許可中,並且它仍然是一樣的 – Code 2014-12-19 10:43:49

+0

這肯定是問題的一部分。另外什麼是'FileLocation'的實際價值? – 2014-12-19 10:43:50

+0

@Dura FileLocation作爲'C:\ Test \ Files'存儲在數據庫中。 – Code 2014-12-19 10:44:31

回答

0

你的問題可能是你試圖訪問一個目錄。

從MSDN文檔有關的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 '' 

你確定你實際上得到的文件名後面?或者只是目錄,就像上面代碼片段的第二個例子。

+0

我從數據庫中獲得'FileName'&'Location'作爲'List'返回的數據庫。當用戶點擊下載按鈕,它的意思是通過文件名,並允許他們下載 – Code 2014-12-19 10:55:56

+0

這是_meant to_。附上調試器並檢查確實是這種情況。 – CodeCaster 2014-12-19 10:56:50

+0

@CodeCaster在調試的'CommandArgument'值是'C:\測試\ Files' ' – Code 2014-12-19 11:01:57