C# function similar to PHP file_get_contents


Here is a C# function that works similar to the PHP function file_get_contents. The given C# function 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.

/// <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();
return sContents;

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.

Hope you find it useful.

C# function similar to PHP file_get_contents  (4466 Views)