views:

285

answers:

3

I want to include certain files in my page. I'm not always sure if they exists, so I have to check if they do. (Otherwise the page crashes, as you probably know)

<%@ 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>

While the include works, the code checking if the file exists does not.

If I remove this code:

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

Everything runs fine. I also tried putting it in a <script runat="server"> block, but it still failed.

+2  A: 

Try

exists = System.IO.File.Exists(Server.MapPath("~/extra/file/test.txt"));
John Boker
The Server.MapPath did it, indeed. The tilde did add a few maps to the structure, so I had to remove it, but still: success.
skerit
+1  A: 

Server side includes (SSI) are executed before your code, so you can't do this way.

If your included file is just static information (i.e. without server-side code), you can do something like:

string file = Server.MapPath("~/extra/file/test.txt");
if(System.IO.File.Exists(file))
{
    Response.Write(System.IO.File.ReadAllText(file));
}
Rubens Farias
It's going to be content, indeed. This works like a charm.
skerit
+2  A: 

Server-side includes are legacy ASP code and cannot be conditional. However, since you are using C# ASP.NET code, you can just read the file and output it using C# instead of the server-side include.

Here, if you get an error with your code, it is probably because something else is not configured properly for you to use it (security settings, maybe?).

Jason Kealey