概述
/************************
*用第二个方法,获取远程文件的大小
*************************/
//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;
}
最后
以上就是隐形春天为你收集整理的C# 判断图片链接是否存在的全部内容,希望文章能够帮你解决C# 判断图片链接是否存在所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复