Search code examples
c#phphttpwebrequest

PHP works fine via browser, won't work via HttpWebRequest


My goal

I'm trying to read and write files from my webserver via C#.

Progress

So far, via PHP I made it to work that you can write to files with file_put_contents(). The saved files are text files, so you can easily read them. My C# program with responses works fine, and I get my desired values.

    private string GetWarnInfo(string id)
        {
            try
                {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"http://example.com/{id}.txt");
                request.Method = "GET";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    return reader.ReadToEnd();
            }
            }
            catch(Exception)
            {
                return null;
            }
        }

100% of the time it did not return null, which is a success.

The problem

Well, the writing. My PHP in example.php looks like this:

if (file_exists($_GET['id'] . '.txt'))
{
    unlink($_GET['id'] . '.txt');
    file_put_contents($_GET['id'] . '.txt', $_GET['info']);
} else {
    file_put_contents($_GET['id'] . '.txt', $_GET['info']);
}

While it fully works via browser calls (http://example.com/example.php?id=23&info=w3), and actually makes the text file, I can't get it to work with C#:

    public void ServerRequest(string id, string info)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com/example.php?id=" + id + "&info=" + info);
        request.Method = "GET";
    }

For example, I call ServerRequest((23).ToString(), "w3"), but the file won't change, it will always be either non-existant or in it last state (if there was one).

What could cause this problem? How would I fix it?


Solution

  • Thanks to @Barmar

    I have figured out the problem, if I don't call GetResponse(), it will never start the web request. After doing that, everything worked fine!