http方式获取远程文件内容

Posted yaosj

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了http方式获取远程文件内容相关的知识,希望对你有一定的参考价值。

 

    public class HttpServer
    
        /// <summary>
        /// 读取远程文件的内容
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string ReadFromFile(string serverFilePath)
        
            if (string.IsNullOrEmpty(serverFilePath))
                return "";

            string ret = "";
            HttpWebRequest req = null;
            HttpWebResponse resp = null;

            try
            
                req = (HttpWebRequest)HttpWebRequest.Create(serverFilePath);
                req.Method = "GET";
                req.KeepAlive = false;

                resp = req.GetResponse() as HttpWebResponse;
                using (Stream stream = resp.GetResponseStream())
                
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    
                        ret = reader.ReadToEnd();
                    
                
            
            catch (Exception ex)
            
                throw ex;
            
            finally
            
                if (req != null)
                    req.Abort();
                if (resp != null)
                    resp.Close();
            

            return ret;
        

        /// <summary>
        /// 读取远程文件的内容(异步)
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public async Task<string> ReadFromFileAsync(string serverFilePath)
        
            if (string.IsNullOrEmpty(serverFilePath))
                return "";

            string ret = "";
            HttpWebRequest req = null;
            HttpWebResponse resp = null;

            try
            
                req = (HttpWebRequest)HttpWebRequest.Create(serverFilePath);
                req.Method = "GET";
                req.KeepAlive = false;

                resp = req.GetResponse() as HttpWebResponse;
                using (Stream stream = resp.GetResponseStream())
                
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    
                        ret = await reader.ReadToEndAsync();
                    
                
            
            catch (Exception ex)
            
                throw ex;
            
            finally
            
                if (req != null)
                    req.Abort();
                if (resp != null)
                    resp.Close();
            

            return ret;
        
    

 

以上是关于http方式获取远程文件内容的主要内容,如果未能解决你的问题,请参考以下文章

php如何获取远程文件内容的函数

Git 获取远程仓库指定分支内容

JQuery,JS 读取远程服务器的txt文件内容

php如何获取文件内容?

php 如何下载远程文件到本地重命名

php自动下载远程文件问题