我想将一些简单的用户数据存储到我服务器上的JSON文件中,这样我就可以将它与我的PHP一起使用。我知道如何创建一个JSON文件,这要归功于这篇方便的文章:How to write a Json file in C#?但是在本文中他们将文件保存在本地,但是我希望它将它保存在我的外部服务器上,但是我不知道从来没有这样做过之前真的使用过JSON。有人可以告诉我它是否可能,以及我需要使用哪种方法?我认为这样的事情会起作用,至少对我来说似乎是合理的:
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();
}
这导致了一次失败,因为它没有做任何事情。这是因为我之前从未使用过JSON。
如果有可能,有人可以教我一个很好的方法吗?
答案 0 :(得分:0)
对于迟到的回答感到抱歉,但我得到了正确的代码。而不是HttpWebRequest我只需要使用WebRequest,而且我也必须在我的uri字符串中使用ftp而不是http。这是我的最终代码:
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();
}
}
}
另外,谢谢gusman的精彩提示!