///1.判斷遠程文件是否存在
///fileUrl:遠程文件路徑,包括IP地址以及詳細的路徑
private bool RemoteFileExists(string fileUrl)
{
bool result = false;//下載結果
WebResponse response = null;
try
{
WebRequest req = WebRequest.Create(fileUrl);
response = req.GetResponse();
result = response == null ? false : true;
}
catch (Exception ex)
{
result = false;
}
finally
{
if (response != null)
{
response.Close();
}
}
return result;
}
/// 2.通過傳入的url獲取遠程文件數據(二進制流),大家可以通過Response.BinaryWrite()方法將獲取的數據流輸出
/// </summary>
/// <param name="url">圖片的URL</param>
/// <param name="ProxyServer">代理服務器</param>
/// <returns>圖片內容</returns>
public byte[] GetFile(string url, string proxyServer)
{
WebResponse rsp = null;
byte[] retBytes = null;
try
{
Uri uri = new Uri(url);
WebRequest req = WebRequest.Create(uri);
rsp = req.GetResponse();
Stream stream = rsp.GetResponseStream();
if (!string.IsNullOrEmpty(proxyServer))
{
req.Proxy = new WebProxy(proxyServer);
}
using (MemoryStream ms = new MemoryStream())
{
int b;
while ((b = stream.ReadByte()) != -1)
{
ms.WriteByte((byte)b);
}
retBytes = ms.ToArray();
}
}
catch (Exception ex)
{
retBytes = null;
}
finally
{
if (rsp != null)
{
rsp.Close();
}
///將本地文件通過httpwebrequest上傳到服務器
///localFile:本地文件路徑及文件名稱,uploadUrl:遠程路徑(虛擬目錄)
///在遠程路徑中需要把文件保存在的文件夾打開權限設置,否則上傳會失敗
public bool UploadFileBinary(string localFile, string uploadUrl)
{
bool result = false;
HttpWebRequest req = null;
Stream reqStream = null;
FileStream rdr = null;
try
{
req = (HttpWebRequest)WebRequest.Create(uploadUrl);
req.Method = "PUT";
req.AllowWriteStreamBuffering = true;
// Retrieve request stream
reqStream = req.GetRequestStream();
// Open the local file
rdr = new FileStream(localFile, FileMode.Open);
byte[] inData = new byte[4096];
int bytesRead = rdr.Read(inData, 0, inData.Length);
while (bytesRead > 0)
{
reqStream.Write(inData, 0, bytesRead);
bytesRead = rdr.Read(inData, 0, inData.Length);
}
rdr.Close();
reqStream.Close();
req.GetResponse();
result = true;
}
catch (Exception e)
{
result = false;
}
finally
{
if (reqStream != null)
{
reqStream.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
return result;
}
}
return retBytes;
}
本文轉載於:http://www.cnblogs.com/tsgx108/archive/2008/11/18/1335618.html感謝原作者的貢獻。轉載請著名出處
