DAV - Distributed Authoring and Versioning
I am going through the process of Uploading and Deleting Files on a remote webserver. When doing this I needed the ability to take a stream object and save it to a remote server. A bit different than the UploadFile() method on System.Net.WebClient.
It was a bit of a pain, so I figured I'd share it with others in order to save them the trouble.
public static WebResponse UploadFile( Stream _inputStream, NetworkCredential _cred, string _httpAddress ){
// setup request
WebRequest request = WebRequest.Create( _httpAddress );
request.Credentials = _cred;
request.Method = "PUT";
request.ContentLength = _inputStream.Length;
// create byte array
byte[] byt = new Byte[ checked( ( uint )Math.Min( 8192, _inputStream.Length ) ) ];
// setup input/output streams
Stream outputStream = null;
try
{
outputStream = request.GetRequestStream();
// now write the stream
int bytesRead = 0;
do
{
bytesRead = _inputStream.Read( byt, 0, byt.Length );
if( 0 == bytesRead ) continue;
outputStream.Write( byt, 0 , bytesRead );
}
while( 0 != bytesRead );
return request.GetResponse();
}
finally
{
// overkill, but it doesn't hurt.
if( null != outputStream )
{
outputStream.Flush();
outputStream.Close();
outputStream = null;
}
// don't bother closing the input stream. we do not own it.
}
}
I also needed to delete a file on a remote server. This code is based on some code I found on MSDN WebDAVDelete
public static WebResponse DeleteHttpFile( string _uri, NetworkCredential _cred )
{
WebRequest request = WebRequest.Create( _uri );
request.Credentials = _cred;
request.Method = "DELETE";
return request.GetResponse();
}