【问题标题】:ASP.Net a list of files in a directory + link to fileASP.Net 目录中的文件列表 + 文件链接
【发布时间】:2011-08-24 04:58:23
【问题描述】:

我正在创建一个 Web 表单,它将显示目录中的异常文件列表。文件显示正常,但是链接不起作用。我已经对解决方案进行了一些快速搜索,唯一的问题是大多数解决方案都要求我设置一个虚拟目录,但是这些文件所在的服务器不是 Web 服务器。这是列出文件的代码:

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 来设置?

【问题讨论】:

标签: c# asp.net html iis webforms


【解决方案1】:

如果文件与 Web 服务器不在同一台服务器上,则无法在没有虚拟目录的情况下执行此操作。这些文件需要通过网络服务器提供给客户端。

虽然您可以使用 IIS Express 创建虚拟目录 - 请查看 this discussion thread。您可能还需要启用对 IIS Express 的外部访问(this post on WebMatrix 在这方面应该会有所帮助)。注意:使用虚拟目录时,您的 URL 需要使用 http:https: 方案而不是 file:

另一种方法是将要共享的文件上传到网络服务器上的某个位置,然后从网络服务器提供它们。

【讨论】:

    【解决方案2】:

    如果引用本地文件系统,需要将超链接格式化如下:

    file:///c:/myfile.txt

    【讨论】:

      【解决方案3】:

      我认为您可以使用下载器服务器端来实现这一点,它可以为您访问文件,然后通过 http 提供它们。

      一个httphandler,它的ProcessRequest方法可以(非常简化)如下:

      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();
          }   
      }
      

      然后您将构建链接以将文件作为参数指向您的处理程序:

      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>
      

      (当然这个示例很简单,我认为错误很多,但只是为了说明问题)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-11
        • 2012-05-28
        • 1970-01-01
        • 2013-11-05
        • 2011-11-21
        • 1970-01-01
        • 1970-01-01
        • 2013-12-15
        相关资源
        最近更新 更多