Thursday, April 3, 2008

Upload image to web server using webservice .NET

To transfer a file to the web server, it is not necessary to use FTP to upload. You can use webservice to do so. Here is the trick:

public string CreateFileToBase64String(string path)
{
Stream fs = new FileStream(path, FileMode.Open);
MemoryStream ms = new MemoryStream();
const int size = 4096;
byte[] bytes = new byte[4096];
int numBytes;
while ((numBytes = fs.Read(bytes, 0, size)) > 0)
ms.Write(bytes, 0, numBytes);
ms.Close();
fs.Close();
return Convert.ToBase64String(ms.GetBuffer());
}
public void CreateFileFromBase64String(string imageData, string path)
{
MemoryStream msf = new MemoryStream(Convert.FromBase64String(imageData));
Stream stem = new FileStream(path, FileMode.Create);
msf.WriteTo(stem);
msf.Close();
stem.Close();
}

you see things is so simple.

How to get web content from the web .NET

Sometimes I need to download the html content from the internet, therefore this method is very useful.


public static void GetWebContent(string url, string saveToPath)
{
if (IsValidUrl(url))
{
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse();
Stream fs = httpRes.GetResponseStream();
FileStream fss = new FileStream(saveToPath, FileMode.Create);
const int size = 4096;
byte[] bytes = new byte[4096];
int numBytes;
while ((numBytes = fs.Read(bytes, 0, size)) > 0)
fss.Write(bytes, 0, numBytes);
fss.Close();
}
}

Find the image height and width using .NET

See as simple as this:

System.Drawing.Imaging.BitmapData bit = new
System.Drawing.Imaging.BitmapData();
int height = bit.Height;