在将所有字节写入C#之前,无法关闭流

时间:2019-05-28 23:33:36

标签: c# httpwebrequest streamwriter

这是我一段时间以来的第一次C#尝试,但是我已经明白了这一点,也许我认为我需要一些专家的关注。

我一直收到标题中提到的错误。我猜有明显的东西我想念吗?

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace API_Call
{
    class Program
    {
        static void Main(string[] args)
        {
            var watch = new Stopwatch();
            HttpWebRequest request = HttpWebRequest.Create("http://bk-pim/Perfion/GetData.asmx") as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "text/xml";
            request.Headers.Add("SOAPAction","http://perfion.com/ExecuteQuery");
            //FileInfo info = new FileInfo(@"C:\Users\dcoats\Desktop\mytestfile.txt");
            //long size = info.Length;
            //request.ContentLength = size;


            using (var stream = request.GetRequestStream())
            using (var writer = new StreamWriter(stream))
            {
                var body = WebUtility.HtmlEncode(File.ReadAllText(@"C:\Users\dcoats\Desktop\mytestfile.txt"));
                body = "<?xml version=\"1.0\" encoding=\"utf - 8\"?>< soap:Envelope xmlns:soap = \"http://schemas.xmlsoap.org/soap/envelope/\" xmlns: xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xmlns: xsd = \"http://www.w3.org/2001/XMLSchema\" >< soap:Body >< ExecuteQueryResponse xmlns = \"http://perfion.com/\" >< ExecuteQueryResult >" + body + "</ExecuteQueryResult></ ExecuteQueryResponse ></ soap:Body ></ soap:Envelope > ";

            }


            watch.Start();
            var response = request.GetResponse(); //bombs here
            watch.Stop();
            response.GetResponseStream();

            Console.WriteLine();
            Console.ReadLine();
            Console.WriteLine(watch.ElapsedMilliseconds);
            Console.ReadLine();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您要求与Web服务进行交互的更好方法:

  • 在SOLUTION EXPLORER中右键单击参考
  • 选择添加服务参考
  • 输入服务所在的网址-例如 http://bk-pim/Perfion/GetData.asmx http://www.dneonline.com/calculator.asmx
  • 选择名称空间/设置其他选项
  • 点击确定
  • 创建一个客户端(我无法使用您的Web服务,因此此答案现在切换为使用DNEOnline的计算器,并选择命名空间为“ Calc”):

Calc.CalculatorSoapClient sc = new Calc.CalculatorSoapClient();

  • 客户端上的调用方法:

int result = sc.Add(1,2);

就是这样-没有套接字,没有构建XML等-服务引用创建了一组对象和类来完成所有这些工作