/// 1. Determine whether the remote file exists
/// FileUrl: Specifies the remote file path, including the IP address and detailed path.
Private bool RemoteFileExists (string fileUrl)
{
Bool result = false; // download result
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. obtain remote file data (binary stream) through the input url. You can use the Response. BinaryWrite () method to output the obtained data stream.
/// </Summary>
/// <Param name = "url"> image URL </param>
/// <Param name = "ProxyServer"> proxy server </param>
/// <Returns> image content </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 ();
}
/// Upload a local file to the server through httpwebrequest
/// LocalFile: local file path and file name, uploadUrl: remote path (virtual directory)
/// Set the permission to open the folder where the file is saved in the remote path. Otherwise, the upload will fail.
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;
}