如何获取网络上的文件属性?

    昨天有个网友问到这个问题,简略回复之后,自己再实践了一下,在这里将实践的思路及代码写到这里。

    一、思路

使用WebRequest来向服务器请求文件信息,然后在WebResponse中获取文件信息。(注意:只能获取http、https、ftp、file协议下的文件)

    二、代码

    在这里用类WebFileInfo封装了获取操作。
using System;
using System.Text;
using System.Net;

namespace Wuya.WebFileInfo
{
    /// <summary>
    /// WebFileInfo类,用来获取网站上的文件信息,如大小、创建日期等。
    /// </summary>
    class WebFileInfo
    {
        //成员
        private string url;                     //需要获取文件对应的url地址
        private string userName;                //用户名
        private string password;                //密码
        private bool canGetInfoNow;             //是否可以取得文件的信息了
        private WebHeaderCollection headers;    //获取到的文件头集合
        //属性
        public bool CanGetInfoNow               //现在是否能够取得文件信息
        {
            get
            {
                return canGetInfoNow;
            }
        }
        public string Url                       //url地址
        {
            get
            {
                return url;
            }
            set
            {
                url=value;
                canGetInfoNow=GetWebFileInfo();
            }
        }
        public WebHeaderCollection Headers      //文件头
        {
            get
            {
                return headers;
            }
        }
        //索引器
        public string this[string itemName]
        {
            get
            {
                string strReturn = "";
                try
                {
                    int index = -1;
                    for (int i = 0; i < headers.Count; i++)
                    {
                        if (itemName == headers.GetKey(i))
                        {
                            index = i;
                            break;
                        }
                    }
                    if (index != -1)
                        strReturn = headers.Get(index);
                }
                catch
                {
                }
                return strReturn;
            }
        }
        public string this[FileInfo fileInfo]
        {
            get
            {
                string itemName="";
                switch (fileInfo.ToString())
                {
                    case "Size":
                        itemName = "Content-Length";
                        break;
                    case "Type":
                        itemName = "Content-Type";
                        break;
                    case "CreatedTime":
                        itemName = "Date";
                        break;
                    case "LastModifiedTime":
                        itemName = "Last-Modified";
                        break;
                    default:
                        itemName = "";
                        break;
                }
                if (itemName == "")
                    return "";
                else
                    return this[itemName];
            }
        }
        /// <summary>
        /// 不带参数的构造函数
        /// </summary>
        public WebFileInfo():this("")
        {
        }
        /// <summary>
        /// 带地址的构造函数(使用匿名用户)
        /// </summary>
        /// <param name="url">url地址</param>
        public WebFileInfo(string url):this(url,"","")
        {
        }
        /// <summary>
        /// 带地址,用户,密码的构造函数
        /// </summary>
        /// <param name="url">url地址</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        public WebFileInfo(string url, string userName, string password)
        {
            this.url = url;
            this.userName = userName;
            this.password = password;
            canGetInfoNow=GetWebFileInfo();
        }
        //方法
        /// <summary>
        /// 获取url对应文件的信息
        /// </summary>
        /// <returns>返回操作是否成功</returns>
        private bool GetWebFileInfo()
        {
            return GetWebFileInfo(url,userName,password,out headers);
        }
        /// <summary>
        /// 获取url对应文件的信息,并保存到headers中
        /// </summary>
        /// <param name="url">url地址</param>
        /// <param name="headers">保存得到的信息</param>
        /// <returns>返回操作是否成功</returns>
        public static bool GetWebFileInfo(string url, out WebHeaderCollection headers)
        {
            return GetWebFileInfo(url, "", "", out headers);
        }
        /// <summary>
        /// 获取url对应文件的信息,并保存到headers中
        /// </summary>
        /// <param name="url">url地址</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="headers">保存得到的信息</param>
        /// <returns>返回操作是否成功</returns>
        public static bool GetWebFileInfo(string url,string userName,string password,out WebHeaderCollection headers)
        {
            bool isSuccessed=false;
            headers=null;
            if(url==null || url.Trim()=="")
                return false;
            WebRequest request=null;
            WebResponse response=null;
            try
            {
                request = WebRequest.Create (url);
                if (userName != null && userName != "")
                    request.Credentials = new NetworkCredential(userName, password);
                response = request.GetResponse ();
                if(response.Headers!=null)
                {
                    isSuccessed=true;
                    headers=response.Headers;
                }
            }
            catch
            {
                isSuccessed=false;
                headers=null;
            }
            finally
            {
                if(response!=null)
                    response.Close();
            }
            return isSuccessed;
        }
        /// <summary>
        /// 获取文件大小(单位:字节)
        /// </summary>
        /// <returns>返回文件大小</returns>
        public int GetFileSize()
        {
            string strSize = this[FileInfo.Size];
            int size = 0;
            try
            {
                size = int.Parse(strSize);
            }
            catch
            {
                size = 0;
            }
            return size;
        }
        /// <summary>
        /// 获取文件类型
        /// </summary>
        /// <returns>返回文件类型</returns>
        public string GetFileType()
        {
            return this[FileInfo.Type];
        }
        /// <summary>
        /// 获取文件的创建时间
        /// </summary>
        /// <returns>返回文件的创建时间,如果失败,返回DateTime.MinValue</returns>
        public DateTime GetFileCreatedTime()
        {
            string strCreatedTime = this[FileInfo.CreatedTime];
            DateTime createdTime;
            if (strCreatedTime == "")
                createdTime = DateTime.MinValue;
            else
            {
                try
                {
                    createdTime = DateTime.Parse(strCreatedTime);
                }
                catch
                {
                    createdTime = DateTime.MinValue;
                }
            }
            return createdTime;
        }
        /// <summary>
        /// 获取文件的修改时间
        /// </summary>
        /// <returns>返回文件的修改时间,如果失败,返回DateTime.MinValue</returns>
        public DateTime GetFileLastModifiedTime()
        {
            string strLastModifiedTime = this[FileInfo.LastModifiedTime];
            DateTime lastModifiedTime;
            if (strLastModifiedTime == "")
                lastModifiedTime = DateTime.MinValue;
            else
            {
                try
                {
                    lastModifiedTime = DateTime.Parse(strLastModifiedTime);
                }
                catch
                {
                    lastModifiedTime = DateTime.MinValue;
                }
            }
            return lastModifiedTime;
        }
    }

    /// <summary>
    /// 枚举:网络文件信息
    /// </summary>
    public enum FileInfo
    {
        Size,               //Content-Length    文件大小
        Type,               //Content-Type      文件类型
        CreatedTime,        //Date    Sun, 26 Mar 2006 03:42:45 GMT   创建时间
        LastModifiedTime    //Last-Modified    Tue, 21 Mar 2006 14:52:00 GMT 修改时间
    }
}

    三、调用示例

            //首先创建一个WebFileInfo的实例(如果要访问需要身份认证的文件,请使用带用户,密码的构造函数)
            WebFileInfo webFileInfo = new WebFileInfo(txtUrl.Text.Trim());
            //这里检查是否能够获取文件的信息了
            if (webFileInfo.CanGetInfoNow)
            {
                StringBuilder sbFileInfo = new StringBuilder();
                sbFileInfo.Append("键        值/r/n");
                //访问属性Headers可以获取服务器返回的所有信息,(当然,使用webFileInfo[itemName]也可以获取所有的信息)
                for (int i = 0; i < webFileInfo.Headers.Count; i++)
                {
                    sbFileInfo.Append(webFileInfo.Headers.GetKey(i));
                    sbFileInfo.Append("    ");
                    sbFileInfo.Append(webFileInfo.Headers.Get(i));
                    sbFileInfo.Append("/r/n");
                }
                txtInfo.Text = sbFileInfo.ToString();
                //这里使用2个公共方法来分别获取文件大小和创建日期
                txtInfo.Text += "/r/n文件大小:" + webFileInfo.GetFileSize();
                txtInfo.Text += "/r/n创建日期:" + webFileInfo.GetFileCreatedTime();
            }

你可能感兴趣的:(网络,String,服务器,null,url,System)