【问题标题】:Cannot close stream until all bytes are written c#在写入所有字节之前无法关闭流c#
【发布时间】:2019-05-28 23:33:35
【问题描述】:

这是我一段时间以来的第一次 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();
        }
    }
}

【问题讨论】:

  • 你为什么要创建StreamWriter?你似乎没有在任何地方使用它。我认为是时候清理你的代码了。
  • 您根本没有将body 写入writer
  • 你到底想做什么?从 C# 与 Web 服务交互有比手动将字符串连接形成的 xml 推入套接字更好的最简单方法
  • @CaiusJard 这正是我想要做的。看到我对 c# 不是那么精通,我发现自己在谷歌上搜索它。我的意思是,如果你有更好的方法,我会全力以赴。

标签: c# httpwebrequest streamwriter


【解决方案1】:

您要求一种更好的方式与网络服务交互:

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

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

  • 在客户端调用方法:

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

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

【讨论】:

  • 我会试试这个,看看效果如何。我能够弄清楚我的问题,但我确实喜欢简单。
  • 这种方式不仅简单;将一组对象序列化和反序列化到 XML 和从 XML 序列化和反序列化远比通过切割字符串将它们组合在一起更正确 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2015-05-04
  • 1970-01-01
  • 2013-09-25
  • 2010-09-20
相关资源
最近更新 更多