GetImage, huagai
Check whether the path is valid and the network access address. Notfound cannot be found, and the number of httpstatuscode enumerations is large, just set it as needed.
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; }
Obtain image data based on the network address or local path and save it to a local file. Note that the data stream permission is FileAccess. ReadWrite.
An error may occur when saving. try catch is set on the outer layer. However, it is better to judge each section and get the error point.
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(); }