ASP File_Get_Contents and File_Put_Contents

As I've become more of a PHP developer than an ASP developer, one thing I've noticed is that it is 10x easier to read/write text files with PHP. Simply use file_get_contents() and be done. ASP isn't so nice. But it can be done, so I'm creating those for simplicity here:

<%
Function File_Get_Contents(strFile)
	' Remote File
	If Left(strFile, 7) = "http://" Or Left(strFile, 8) = "https://" Then
		Set objXML = Server.CreateObject("Microsoft.XMLHTTP")
		' Use this line if above errors
		'Set objXML = Server.CreateObject("MSXML2.ServerXMLHTTP")
		objXML.Open "GET", strFile, False
		objXML.Send()
		File_Get_Contents = objXML.ResponseText()
		Set objXML = Nothing
	' Local File
	Else
		Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
		Set objFile = objFSO.OpenTextFile(strFile, 1)
		File_Get_Contents = objFile.ReadAll()
		Set objFile = Nothing
		Set objFSO = Nothing
	End If
End Function

Function File_Put_Contents(strFile, strContents, blnAppend)
	If blnAppend Then
		intMode = 8
	Else
		intMode = 2
	End If
	Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
	Set objFile = objFSO.OpenTextFile(strFile, intMode, True)
	objFile.Write(strContents)
	Set objFile = Nothing
	Set objFSO = Nothing
End Function
%>

Of course this file_get_contents doesn't support remote URLs, but it can easily be added.

EDIT: I just added remote URL support.

7 thoughts on “ASP File_Get_Contents and File_Put_Contents”

  1. Do you have a suggestion on how to adapt file_get_contents to support a remote URL using Classic ASP? Like others I am reluctant to make the move from Classic ASP to ASP.NET

  2. Thanks Dan! I tested your remote url support and was getting an error. I found that you this “File_Get_Contents = objXML.ResponseText()” should be changed to this “File_Get_Contents = objXML.ResponseText”

  3. Hi Dan, Thanks for the great code…it’s save us a lot of trouble. I’m new to coding with ASP and was wondering if you could kindly post an example of how we would use your functions. I’ve managed to execute you File_Get_Contents() function, but I can’t seem to get the File_Put_Contents() function to work.

Leave a Reply

Your email address will not be published. Required fields are marked *