As a follow-up on my previous post about pulling data from a web site, this post is about doing it the other way -- uploading data to a web site.
Let's first fill a byte array with some content, usually from a file (or database) like this (require a reference to System.IO)...
FileStream fs = File.OpenRead("file.any");
BinaryReader br = new
BinaryReader(fs);
byte[] data = br.ReadBytes((int)br.BaseStream.Length);
br.Close();
fs.Close();
...and then the code to upload looks like this (require an additional reference to System.Net)...
string url = "http://www.businessanyplace.net/file.any";
Uri uri = new
Uri(url);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "PUT";
request.Credentials = new
NetworkCredential("UserName", "P@ssW0rd");
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
// For large files (> 50KB) you may want to uncomment the next line
//request.SendChunked = true;
request.ContentLength = data.Length;
Stream s = request.GetRequestStream();
s.Write(data, 0, data.Length);
s.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
HttpStatusCode code = response.StatusCode;
string result = code.ToString();
...and this works just as well for text files as for any binary file. Please note that the user needs to have write access to the virtual directory (and the physical disk location) where the file is to be written. For a more complete example of how files (media) can be compressed (zipped) and uploaded to a Web site, see the source code for my article Claims2Go: Claims Processing for Windows Mobile-Based Devices.