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(); }