B. Hulshof B. Hulshof - 5 months ago 29
JSON Question

Is it possible to save JSON file to a server

I want to store some simple user data to a JSON file on my server so I can use it with my PHP. I know how to create a JSON file thanks to this handy article: How to write a Json file in C#? But in this article they save the file locally but I want it to save it on my external server but don't know how since I never really used JSON before. Can someone tell me if it's possible and so how what kind of method do I need to use? I thought something like this would work, atleast it seemed reasonable to me:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://" + ConfigurationManager.AppSettings["jsonuri"] +"/apptest/saleskickerbuffer.txt");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";

using (var sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
if(reqCat == "bvg")
{
json = "{\"bedrijfsNaam\":\"" + bedrijfsNaam + "\"," +
"\"ContPers\":\"" + ContPers + "\"," +
"\"TelNum\":\"" + TelNum + "\"," +
"\"email\":\"" + email + "\"," +
"\"Land\":\"" + Land + "\"," +
"\"Plaats\":\"" + Plaats + "\"," +
"\"PostCode\":\"" + PostCode + "\"}";
MessageBox.Show(json);
}

sw.Write(json);
sw.Flush();
sw.Close();
}


This resulted in a failure ofcourse because it did nothing. This is bacause I have never used JSON before.

Can someone teach me a good method for this if it's posssible?

Answer

Sorry for the late answer but I got the right code. Instead of HttpWebRequest I had to use just WebRequest and in I also had to use ftp instead of http in my uri string. Here is my final code:

    static string ftpUser = ConfigurationManager.AppSettings["ftpUser"].ToString();
    static string ftpPass = ConfigurationManager.AppSettings["ftpPass"].ToString();

    static string serverPath = ConfigurationManager.AppSettings["jsonuri"].ToString() + dt.bedrijfsNaam + ".json";

    static string json;

    public static void post(string reqCat)
    {
        WebRequest hwr = WebRequest.Create(serverPath);
        hwr.Method = WebRequestMethods.Ftp.UploadFile;
        hwr.Credentials = new NetworkCredential(ftpUser, ftpPass);

        if (reqCat == "bvg")
        {
            json = "[\"bedrijfsNaam\":\"" + bedrijfsNaam + "\"," +
                            "\"ContPers\":\"" + ContPers + "\"," +
                            "\"TelNum\":\"" + TelNum + "\"," +
                            "\"email\":\"" + email + "\"," +
                            "\"Land\":\"" + Land + "\"," +
                            "\"Plaats\":\"" + Plaats + "\"," +
                            "\"PostCode\":\"" + PostCode + "\"]";
            using (var sw = new StreamWriter(hwr.GetRequestStream()))
            {
                sw.Write(json);
                sw.Flush();
                sw.Close();
            }
        }
    }

Also, thank you gusman for the great tip!

Comments