【问题标题】:"This stream does not support seek operations" while HTTPWebRequest making [closed]HTTPWebRequest 制作时“此流不支持查找操作”[关闭]
【发布时间】:2016-04-13 16:05:49
【问题描述】:

我有这样一段代码:

var uri = "myURL.com"
var request = (HttpWebRequest)WebRequest.Create(uri);
string postData = "myData";
byte[] data = Encoding.UTF8.GetBytes(postData);

request.Method = "POST";
request.UseDefaultCredentials = true;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
request.AddRange(1024);
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36";

Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine(responseString);
response.Close();
stream.Close();

我得到一个异常,例如:“此流不支持查找操作”。在stream.Lengthstream.Position 中出现此错误。虽然我认为,由于这个错误,我的postData没有发送到服务器。 Here is the screenshot of the exception

【问题讨论】:

  • 在女巫线上是错误的吗?你也可以提供堆栈跟踪吗?
  • 这不完全是一个错误,而是一个异常(我在屏幕截图中显示了这一点)。但是,例如,当我写像stream.Position = 0; 这样的东西时,我会收到类似的错误消息:An unhandled exception of type 'System.NotSupportedException' occurred in System.dll. Additional information: This stream does not support seek operations.
  • 问题的解决方法:将stream.Close();从代码末尾放在request.GetResponse()之前。在流关闭之前它无法获得响应。

标签: c# stream httpwebrequest


【解决方案1】:

仅当您调用与当前流(在您的情况下为 NetworkStream)不兼容的方法或属性时才会引发此异常。如果需要向后移动,则需要将内容复制到临时流(MemoryStream、FileStream、...)中。

您的示例代码在这种情况下没有问题。您可以在 Visual Studio 中看到的异常是因为 VS 尝试访问每个属性以显示一个值。当您的代码运行时,不会调用诸如“位置”之类的属性,并且一切都很好。

以编程方式了解您是否可以在流中查找。使用流的属性CanSeek

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多