Having Issues Making HTTP Post Request in C#

Caleb Rinderer 1 Reputation point
2021-06-10T18:44:59.28+00:00

I have written some code in C# that compiles and runs perfectly on its own, but when I try to put it into a Visual Studio windows form application, I keep running into errors. The code in question sends a POST request to a local device and then downloads the response as a CSV. I can run this without any errors typically. But when I run it through the Visual Studio program I get the following error:
The underlying connection was closed unexpectedly.

I am making both requests on the same device to the same "server" so there has to be something with the .NET framework that's tripping me up I am guessing. Here is the code:

            var url = "http://local.ip.address/";
            using (var wb = new WebClient())
            {
                var data = new NameValueCollection();
                data["data_val1"] = "data";
                data["data_val2"] = "data";
                data["data_val3"] = "data";
                data["data_val4"] = "data";
                data["data_val5"] = "data";
                var response = wb.UploadValues(url, "POST", data);
                string responseInString = Encoding.UTF8.GetString(response);
                string path = @"C:\LOCALPATH\httpResponse.csv";
                if (!File.Exists(path))
                {
                    // Create a file to write to.
                    using (StreamWriter sw = File.CreateText(path))
                    {
                        sw.WriteLine(responseInString);
                    }
                }
            }

Any help is appreciated! Thanks!

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,424 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.