开发者

Stream.Length throws NotSupportedException

I'm trying to POST data to a Restful service and getting this error. Any help greatly appreciated.

Length = 'dataStream.Length' threw an exception of type 'System.NotSupportedException'

Position = 'dataStream.Position' threw an exception of type 'System.NotSupportedException'

here is the code

[WebMethod]
//public static void Main(string output)
public string webPost()
{
    //HttpWebResponse response = null; 
    string output = null;

    // Create a request using a URL that can receive a post. 
    WebRequest request = WebRequest.Create("https://subscribers");
    request.PreAuthenticate = true;
    // Set the Method property of the request to POST.        
    request.Credentials = new NetworkCredential("userid", "password");
    request.Method = WebRequestMethods.Http.Post;

    string EmailAddress = "test@test1.com";
    string FirstName = "first";
    string LastName开发者_JS百科 = "Last";

    StringBuilder Efulfill = new StringBuilder();

    Efulfill.Append("EmailAddress" + HttpUtility.UrlEncode(EmailAddress));
    Efulfill.Append("FirstName" + HttpUtility.UrlEncode(FirstName));
    Efulfill.Append("LastName" + HttpUtility.UrlEncode(LastName));

    byte[] byteData = Encoding.UTF8.GetBytes(Efulfill.ToString());

    request.ContentType = "application/xml;charset=ISO-8859-1";

    request.ContentLength = byteData.Length;

    // Get the request stream.
    Stream dataStream = request.GetRequestStream();
    // Write the data to the request stream.
    dataStream.Write(byteData, 0, byteData.Length);
    // Close the Stream object.
    dataStream.Close();
    // Get the response.
    WebResponse response = request.GetResponse();
    // Display the status.
    Console.WriteLine(((HttpWebResponse)response).StatusDescription);
    // Get the stream containing content returned by the server.
    dataStream = response.GetResponseStream();
    // Open the stream using a StreamReader for easy access.
    StreamReader reader = new StreamReader(dataStream);
    // Read the content.
    string responseFromServer = reader.ReadToEnd();
    // Display the content.
    Console.WriteLine(responseFromServer);
    // Clean up the streams.
    reader.Close();
    dataStream.Close();
    response.Close();
    return output;
}


Duplicate of this: information

Reed Copsey answers by stating "Stream.Length only works on Stream implementations where seeking is available. You can usually check to see if Stream.CanSeek is true."


You'll need to cast your Stream to something like a MemoryStream in order for it to be seek-able. Length and Position are invalid on Streams where CanSeek is false.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜