check路径是是否有效,网络访问地址。notfound查找不到,httpstatuscode枚举数较多,根据自己想要的设置就好了。
public bool checkValid(string path) { HttpWebRequest request = HttpWebRequest.Create(path) as HttpWebRequest; request.Method = "GET"; request.ProtocolVersion = new Version(1, 1); HttpWebResponse response = request.GetResponse() as HttpWebResponse; if (response.StatusCode==HttpStatusCode.NotFound) { return false; } return true; }
根据网络地址还是本地路径,进行获取图片数据,保存到本地文件下。注意数据流的权限FileAccess.ReadWrite
保存有可能出错,在外层套了个try catch,不过各个节进行判断更好,能够拿到出错点。
if (url.IndexOf("http://") == 0 || url.IndexOf("https://") == 0) { WebRequest request = (WebRequest)HttpWebRequest.Create(url); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); FileStream fileStream = File.Create(filePath); byte[] buffer = new byte[(int)response.ContentLength]; int numReadByte = 0; while ((numReadByte = stream.Read(buffer, 0, (int)response.ContentLength)) != 0) { fileStream.Write(buffer, 0, numReadByte); } fileStream.Close(); stream.Close(); } else { FileStream fs = File.Open(url, FileMode.Open, FileAccess.ReadWrite, FileShare.Read); FileStream fileStream = File.Create(filePath); Byte[] image = new Byte[(int)fs.Length]; int numReadByte = 0; while ((numReadByte = fs.Read(image, 0, (int)fs.Length)) != 0) { fileStream.Write(image, 0, numReadByte); } fs.Close(); fileStream.Close(); }