如何在远程服务器上写入CSV文件?

时间:2014-10-04 10:58:20

标签: c# .net winforms httpwebrequest streamwriter

我正在尝试将一些输出写入我的服务器上的.csv文件中。我使用以下代码,但文件中仍然没有输出。 意味着什么都没写。 我的代码在这里

void WriteInRegister(DataRow userdata)
        {
            HttpWebRequest reqHTTP;
            StringBuilder result = new StringBuilder();
            try
            {
                reqHTTP = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://10.10.10.10/config/RequestPlacer.csv"));
                reqHTTP.Credentials = new NetworkCredential("usename", "password");

                if (reqHTTP != null)
                {
                    reqHTTP.ContentType = "application/octet-stream";
                    reqHTTP.Method = WebRequestMethods.File.UploadFile;
                }
                string postdata = (userdata[0].ToString() + ",MacId," + DateTime.Now.ToShortDateString()).ToString();
                byte[] text = Encoding.UTF8.GetBytes(postdata);

                reqHTTP.ContentLength = text.Length;

              /* WebClient wcClient = new WebClient();
                wcClient.Credentials = new NetworkCredential("usename", "password");
                wcClient.UseDefaultCredentials = true;*/
                //wcClient.OpenWrite(new Uri("http://10.10.10.10/config/RequestPlacer.csv"), postdata);


                //  string path = System.Web.HttpContext.Current.Server.MapPath("http://10.10.10.10/config/RequestPlacer.csv");
                   reqHTTP.AllowWriteStreamBuffering = true;
                   Stream writer = reqHTTP.GetRequestStream();
                  /* wcClient.Headers.Add("Content-Type", "application/csv");
                   wcClient.UploadString(new Uri("http://10.10.10.10/config/RequestPlacer.csv"), "POST", postdata);*/


                StreamWriter streamwriter = new StreamWriter(writer);
                streamwriter.WriteLine(postdata);
                streamwriter.Close();
            }
            catch (Exception exe)
            {
                MessageBox.Show(exe.Message);
            }
        }

异常是(“请求已中止:请求已取消。”)

1 个答案:

答案 0 :(得分:0)

我认为问题在于您写入流的内容与Content-Length标题中指定的长度不匹配:因为您使用streamwriter.WriteLine,您还会写回车+在您发送的内容长度中未计入的换行符。

例如,如果您的postdata"foo",则Encoding.UTF8.GetBytes(postdata).Length将返回3,但streamwriter.WriteLine(postdata)实际上会写入"foo\r\n",即5个字节。< / p>

您只需使用Write代替WriteLine(或者如果您想保留内容长度,则计算内容长度中的新行)