2011-05-12 63 views
2

我正在創建一個Web窗體,它將顯示目錄中的異常文件列表。文件顯示正常,但是,鏈接不起作用。我已經做了一些快速搜索解決方案,唯一的問題是大多數解決方案請求我設置了虛擬目錄,但是這些文件所在的服務器不是Web服務器。下面是列出文件的代碼:ASP.Net目錄中的文件列表+鏈接到文件

var exDir = @"\\Server\folder\Exception"; 
     exLabel.Text = ""; 
     foreach (string exFile in Directory.GetFiles(exDir)) 
     { 
      exLabel.Text += @"<a href='file:"+exFile+"'> "+exFile+" </a><br/>"; 
     } 

問題在於我的「href」。有沒有辦法設置這個鏈接而不必設置虛擬目錄?或者如果我必須設置一個,請通過IIS Express來完成?

+0

http://kb.mozillazine.org/Links_to_local_pages_don%27t_work問題是由於Firefox和不是代碼 – bananajunk

回答

2

如果文件與Web服務器不在同一臺服務器上,則不能在沒有虛擬目錄的情況下執行此操作。這些文件需要通過網絡服務器提供給客戶端。

雖然您可以使用IIS Express創建虛擬目錄 - 請看this discussion thread。您可能還需要啓用對IIS Express的外部訪問(this post on WebMatrix在這方面應該會有所幫助)。注意:在使用虛擬目錄時,您的URL將需要使用http:https:方案而不是文件:

另一種方法是將要共享的文件上傳到Web服務器上的某個位置,並通過Web服務器提供。

1

如果引用本地文件系統,你需要按如下格式超鏈接:

文件:/// C:/myfile.txt

1

我認爲你可以在此使用下載服務器端實現,可以爲你訪問這些文件,然後通過http服務它們。

一個HttpHandler,其ProcessRequest方法可以(非常semplified)是這樣的:

public void ProcessRequest(HttpContext context) 
{ 
    if (context.Request.Params["file"] != null) 
    { 
      string filename = context.Request.Params["file"].ToString(); 

     context.Response.Clear(); 
     context.Response.ClearContent(); 
     context.Response.ClearHeaders(); 
     context.Response.Buffer = true; 

     FileInfo fileInfo = new FileInfo(filename); 

     if (fileInfo.Exists) 
     { 
      context.Response.ContentType = /* your mime type */; 
      context.Response.AppendHeader("content-disposition", string.Format("attachment;filename={0}", fileInfo.Name)); 
      context.Response.WriteFile(filename); 
     } 

     context.Response.End(); 
    } 
} 

,那麼你將建立鏈接指向你與文件PARAM處理程序:

var exDir = @"\\Server\folder\Exception"; 
DirectoryInfo dir = new DirectoryInfo(exDir); 

foreach (FileInfo exFile in dir.GetFiles()) 
{ 
    exLabel.Text += @"<a href='downloader.ashx?file="+ exFile.Name + "'> "+exFile.FullName+" </a><br/>"; 
} 

請記住在web.config中設置處理程序:

<system.web> 
    <httpHandlers> 
     ... 
     <add verb="*" path="downloader.ashx" type="YourNamespace.downloader"/> 
    </httpHandlers> 
</system.web> 

(當然這個示例很簡單樂和我認爲充滿錯誤,但只是爲了澄清的方式)