« PreviousNext »

C# method to mimic PHP file_get_contents

14 July 2006

Here is a nifty little function that I wrote to mimic the PHP function file_get_contents. This C# method will read the string contents of a regular file, or a file from a URL (the response from a http request, not the actual file itself).

Notice you have to convert the byte array results to ASCII using the System.Text assembly.

note:
You might be able to read the actual file from the webserver if you replace the DownloadData method on the webclient object to DownloadFile, but this is purely speculation. This kind of action would be useful if you wanted the actual script file not the results from it.

/// <summary>
/// Will return the string contents of a
/// regular file or the contents of a
/// response from a URL
/// </summary>
/// <param name="fileName">The filename or URL</param>
/// <returns></returns>
protected string file_get_contents(string fileName) 
{ 
 string sContents = string.Empty; 
 if (fileName.ToLower().IndexOf("http:") > -1) 
 { // URL 
 System.Net.WebClient wc = new System.Net.WebClient(); 
 byte[] response = wc.DownloadData(fileName); 
 sContents = System.Text.Encoding.ASCII.GetString(response); 
 } else { 
 // Regular Filename 
 System.IO.StreamReader sr = new System.IO.StreamReader(fileName); 
 sContents = sr.ReadToEnd(); 
 sr.Close(); 
 } 
 return sContents;
}

Posted in .NET Programming | Trackback | del.icio.us | Top Of Page

No comments yet

Leave a Reply


You must be logged in to post a comment.