程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> GetImage,華蓋

GetImage,華蓋

編輯:C#入門知識

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

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved