直接上干货:
目录
获取页面中的图片或者MP3文件路径
保存网路图片
保存网络文字
获取页面中的图片或者MP3文件路径
代码语言:javascript复制 /// <summary>
/// 获取网页中的图片路径list集合
/// </summary>
/// <param name="webUrl"></param>
/// <returns></returns>
public static List<string> GetPicUrl(string webUrl) {
HttpClient http = new HttpClient();
Task<string> task = http.GetStringAsync(webUrl);
List<string> list = new List<string>();
Regex reg = new Regex("src="[^"]*[(.jpg)(.png)(.gif)(.bmp)(.ico)]"");
//Regex reg = new Regex("src="[^"]*[(.mp3)]"");
MatchCollection mc = reg.Matches(task.Result);
foreach (Match m in mc)
{
string src = m.Value;
src = src.Replace("src=", "").Replace(""", "");
list.Add(src) ;
}
return list;
}
保存网路图片
代码语言:javascript复制 /// <summary>
/// 下载网络图片
/// </summary>
/// <param name="PicSourceUrl">网络图片地址</param>
/// <param name="filePath">保存本地地址</param>
/// <returns></returns>
public static bool DownPic(string PicSourceUrl, string filePath)
{
WebRequest request = WebRequest.Create(PicSourceUrl);
WebResponse response = request.GetResponse();
Stream reader = response.GetResponseStream();
FileStream writer = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
try
{
byte[] buff = new byte[1024];
int c = 0; //实际读取的字节数
while ((c = reader.Read(buff, 0, buff.Length)) > 0)
{
writer.Write(buff, 0, c);
}
writer.Close();
writer.Dispose();
reader.Close();
reader.Dispose();
response.Close();
}
catch (Exception ex)
{
return false;
}
finally
{
if (writer != null)
{
writer.Close();
writer.Dispose();
}
if (reader != null)
{
reader.Close();
reader.Dispose();
}
if (response != null)
{
response.Close();
}
}
return true;
}
保存网络文字
代码语言:javascript复制 /// <summary>
/// 保存网络文字result到url中
/// </summary>
/// <param name="webUrl">网络文字的http地址</param>
/// <param name="url">网络文字需要保存的地址</param>
public static void SaveTxt(string webUrl,string url) {
HttpClient http = new HttpClient();
Task<string> task = http.GetStringAsync(webUrl);
string result = task.Result;
File.WriteAllText(@url, result);
}