• GetImage


    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();
                    }
    
  • 相关阅读:
    navicat 连接Oracle 报错 ORA-12514 TNS:listener does not currently know of service requested in connect descriptor
    centos 安装配置 redis
    ubuntu安装keras
    VB类似的InputBox为MFC
    WPF颜色选择器
    窗口样式
    IP地址、端口号、子网掩码提交表单库
    添加自定义对话框,您的应用程序
    在c#中使用异步等待构建响应式UI
    一个通用对话框
  • 原文地址:https://www.cnblogs.com/danlis/p/5086376.html
Copyright © 2020-2023  润新知