【问题标题】:Able to include file in ASP.NET, but not check if it exists能够在 ASP.NET 中包含文件,但不检查它是否存在
【发布时间】:2011-01-06 12:43:38
【问题描述】:

我想在我的页面中包含某些文件。 我并不总是确定它们是否存在,所以我必须检查它们是否存在。 (否则页面会崩溃,你可能知道)

<%@ Page Language="C#" %> 

<html>
<body>
<% bool exists;
   exists = System.IO.File.Exists("/extra/file/test.txt");
%> 

Test include:<br>
<!--#include file="/extra/file/test.txt"-->

</body>
</html>

</html>

虽然包含有效,但检查文件是否存在的代码无效。

如果我删除此代码:

<% bool exists;
   exists = System.IO.File.Exists("/extra/file/test.txt");
%> 

一切运行良好。 我也尝试将其放入&lt;script runat="server"&gt; 块中,但仍然失败。

【问题讨论】:

    标签: c# asp.net include file-exists


    【解决方案1】:

    服务器端包含是旧版 ASP 代码,不能是有条件的。但是,由于您使用的是 C# ASP.NET 代码,因此您可以使用 C# 读取文件并输出它,而不是使用服务器端包含。

    在这里,如果您的代码出现错误,可能是因为没有正确配置其他内容以供您使用它(可能是安全设置?)。

    【讨论】:

      【解决方案2】:

      服务器端包含 (SSI) 在您的代码之前执行,因此您不能这样做。

      如果您包含的文件只是静态信息(即没有服务器端代码),您可以执行以下操作:

      string file = Server.MapPath("~/extra/file/test.txt");
      if(System.IO.File.Exists(file))
      {
          Response.Write(System.IO.File.ReadAllText(file));
      }
      

      【讨论】:

        【解决方案3】:

        试试

        exists = System.IO.File.Exists(Server.MapPath("~/extra/file/test.txt"));
        

        【讨论】:

        • Server.MapPath 确实做到了。波浪号确实为结构添加了一些地图,所以我不得不删除它,但仍然:成功。
        猜你喜欢
        • 2023-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-08
        • 1970-01-01
        相关资源
        最近更新 更多