Suppose for some reason you need to use the HTTP PUT verb from the compact framework. Depending on whether you zig before zagging for vice versa, you may expience some unexpected behavior. I'm posting this here in case anyone else has this issue, Google should lead you here and help you out. You may get an uncatchable InvalidOperationException from HttpWebRequest when setting the ContentLength of your request, not on every request just once in a while. The exception is uncatchable because it happens on a worker thread you do not have access to. You can "continue" through it in the debugger but it will otherwise crash your application. The error is as follows:
System.dll!System.Net.HttpWebRequest.set_ContentLength(long value = 108863) + 0xe bytes
System.dll!BufferConnectStream.WritingSucceeds() + 0x12 bytes
System.dll!System.Net.HttpWriteStream.doClose() + 0x4b bytes
System.dll!System.Net.HttpWriteStream.Finalize() + 0x6 bytes
My working Http PUT code:
public bool HttpPut(string path)
{
bool success = false;
string fileName = Image.ImageNameHelper.GetLastPathPart(path);
Uri uri = new Uri("http://bigfatlaptop/put/" + fileName ;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create( uri );
req.AllowWriteStreamBuffering = true;
req.Method = "PUT";
req.KeepAlive = true;
BinaryReader binaryReader = null;
FileStream localFile = null;
Stream reqStream = null;
WebResponse response = null;
try
{
// Allocate buffer for the data, which will be written in blocks.
int bufsize = 4096;
byte[] buf = new byte[ bufsize ];
int xcount;
localFile = File.Open(path, FileMode.Open);
binaryReader = new BinaryReader(localFile);
reqStream = req.GetRequestStream();
req.Expect = string.Empty;
while ( ( xcount = binaryReader.Read( buf, 0, bufsize ) ) > 0 )
{
reqStream.Write( buf, 0, xcount );
}
reqStream.Close();
response = req.GetResponse();
success = true;
}
catch(Exception ex)
{
//do something
}
finally
{
if (null != binaryReader) {binaryReader.Close();}
if (null != response) { response.Close(); }
}
return success;
}
Yes, my development laptop is called "BigFatLaptop". Happy coding.