Hi, I'm very new to ASP... So I have this code on my page <!--#include file="somefile.txt"--> Code (markup): which will show textual content of somefile.txt Now what I want is that if somefile.txt is not found on server, I wan't the content of another textual file to be shown (someotherfile.txt) so I need something like <!--#include file="somefile.txt"--> if file not found then <!--#include file="someotherfile.txt"--> Code (markup): Of course this is not correct code, so that is where I need your help... How do I write this code in ASP? Thanks...
I assume it's ASP Classic (VBScript) .. if so then do as follows: Dim filesys Set filesys = CreateObject("Scripting.FileSystemObject") filesys.CreateTextFile "c:\somefile.txt", True If filesys.FileExists("c:\somefile.txt") Then <!--#include file="somefile.txt"--> Else <!--#include file="someotherfile.txt"--> End If Code (markup):
Btw, if it's an ASP.NET project then you can use the following code: If IO.File.Exists(Server.MapPath("somefile.txt")) Then ' do something Else ' do something else End If Code (markup):
No, that's a common mistake. If the file doesn't exist, the above code is going to throw a compile error and stop the page . An #include is added to the file BEFORE any code is compiled. However, THIS will work: Dim filesys Set filesys = CreateObject("Scripting.FileSystemObject") filesys.CreateTextFile "c:\somefile.asp", True IF filesys.FileExists("c:\somefile.asp") THEN Server.Execute("somefile.asp") ELSE Server.Execute("someotherfile.asp") END IF Code (markup): Understand that while any file you run in Server.Execute will have access to all your variables and session, it will NOT have access to defined subroutines and functions. Let me know if this helps you out!
I agree Include function as is will not work ... however you can use the fylesys object to read the somefile.txt content and show up its content ... Dim content Set content = filesys.OpenTextFile("c:\somefile.asp") Response.Write(f.ReadAll) content.Close Code (markup): However please notice that i am not ASP Classic developer .. i am coding asp.net on daily basis but VBScript is pretty similar to VB.NET anyway, just a little bit trickier. lol
I'm not completely sure but won't using the above code output the code within 'somefile.asp', rather than execute it? Otherwise, if the file is only text and/or HTML then it should work fine.
You have to read text file and execute it with execute(str) in ASP This is the only way to dynamic include a file in ASP