C# 文件处理:使用Config+连接FTP+读取指定目录下所有格式文件(pptx.xls.png.docx.rar.xml等等)

1.将读取下图中所示格式的文件:在这里插入图片描述
2.准备读取程序基路径的函数:
在这里插入图片描述

        /// <summary>
        /// 读取,程序基路径
        /// </summary>
        /// <returns></returns>
        public System.String longwenhGetSystemPath()
        {
            System.String str_result = System.String.Empty;
            try
            {
                //取动态库地址,即.exe文件运行的地址、或Window服务运行启动文件的地址
                System.String str_app_path = System.Reflection.Assembly.GetExecutingAssembly().Location
                //截取除了动态库运行文件名的地址
                    , str_app_path_1 = System.IO.Path.GetDirectoryName(str_app_path);
                return str_app_path_1;
            }
            catch (Exception ex)
            {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter("D:\\log.txt", true))
                {
                    sw.WriteLine(ex.ToString());
                }
                return "error";
            } 
        }

3.准备config文件,并放在指定目录bin\Debug\config\配置文件.config,发布在服务器上的路径为bin\config\配置文件.config:
配置内容:
在这里插入图片描述

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <ftp>
      <FtpIp desc="IP地址">127.0.0.1</FtpIp>
      <FtpHost desc="Ftp端口">25</FtpHost>
      <FtpUser desc="FTP用户名">自身用户名</FtpUser>
      <FtpPass desc="FTP密码">123456</FtpPass>
   </ftp>
</configuration>

配置信息来源请根据下图参照:
在这里插入图片描述
4.读取config内容:
在这里插入图片描述

/// <summary>
        /// 在config读取FTP配置
        /// </summary>
        /// <returns>返回FTP配置信息,结果状态成功返回1,失败返回0</returns>
        public System.Collections.Generic.Dictionary<System.String, System.String> GetFtpMessage()
        {
            System.Collections.Generic.Dictionary<System.String, System.String> dic_result = new System.Collections.Generic.Dictionary<System.String, System.String>();
            dic_result.Add("state", "1");//结果状态:1成功,0失败
            dic_result.Add("msg", "成功");//结果详情。   
            try
            {
                System.String str_app_path = this.longwenhGetSystemPath();
                if (str_app_path.Equals("error"))
                {
                    dic_result["state"] = "0";
                    dic_result["msg"] = "读取,程序基路径失败";
                    return dic_result;
                }
                System.String str_xml_path = str_app_path + "\\config" + "\\配置文件.config";
                System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
                xmlDocument.Load(str_xml_path);
                System.Xml.XmlNode xmlNode = xmlDocument.SelectSingleNode("configuration/ftp");//取Ftp目录 
                System.String str_ftp_ip = xmlNode.SelectSingleNode("FtpIp").InnerText //取FTP服务器地址
                    , str_ftp_port = xmlNode.SelectSingleNode("FtpHost").InnerText//取FTP端口
                    , str_ftp_server = System.String.Format("FTP://{0}:{1}/", str_ftp_ip, str_ftp_port)
                    , str_ftp_user = xmlNode.SelectSingleNode("FtpUser").InnerText//FTP登录的用户名称
                    , str_ftp_pass = xmlNode.SelectSingleNode("FtpPass").InnerText;//FTP登录的密码 
                dic_result.Add("str_ftp_server", str_ftp_server);
                dic_result.Add("str_ftp_port", str_ftp_port);
                dic_result.Add("str_ftp_user", str_ftp_user);
                dic_result.Add("str_ftp_pass", str_ftp_pass); 
            }
            catch (Exception ex)
            { 
                dic_result["state"] = "0";
                dic_result["msg"] = ex.Message;
            }
            return dic_result;
        }

5.读取FTP的相对路径下的文件:
在这里插入图片描述

        /// <summary>
        /// 读取FTP的相对路径下的文件
        /// </summary>
        /// <param name="str_relative_path">FTP相对路径,如“xx/xx”</param>
        /// <returns>返回FTP的文件的集合</returns>
        public System.Collections.Generic.Dictionary<System.String, System.Object> GetFtpDirectoryOrFile(System.String str_relative_path)
        {
            System.Collections.Generic.Dictionary<System.String, System.Object> dic_result = new System.Collections.Generic.Dictionary<System.String, System.Object>();
            dic_result.Add("state", "1");
            dic_result.Add("msg", "成功");
            dic_result.Add("list", null);
            try
            {
                System.String str_ftp_server, str_ftp_port, str_ftp_user, str_ftp_pass
                    , str_ftp_absolute_path = System.String.Empty;//FTP的绝对路径 
                System.Collections.Generic.Dictionary<System.String, System.String> dic_gfm = this.GetFtpMessage();
                System.String str_state = dic_gfm["state"] as System.String
                    , str_msg = dic_gfm["msg"] as System.String;
                if (str_state == "0")
                {
                    dic_result["state"] = "0";
                    dic_result["msg"] = str_msg;
                    return dic_result;
                }
                else
                {
                    str_ftp_server = dic_gfm["str_ftp_server"] as System.String;//ftp地址+端口
                    str_ftp_port = dic_gfm["str_ftp_port"] as System.String;//ftp端口
                    str_ftp_user = dic_gfm["str_ftp_user"] as System.String;//ftp用户
                    str_ftp_pass = dic_gfm["str_ftp_pass"] as System.String;//ftp密码
                }
                System.String strLsFilePath = System.String.Empty;//历史文件路径
                //拼接组合,FTP的绝对路径
                str_ftp_absolute_path = str_ftp_server + str_relative_path;
                System.Net.FtpWebRequest ftp_web_request = null;
                System.Net.WebResponse web_response = null;
                System.IO.StreamReader stream_reader = null;
                System.String str_dir_or_file = System.String.Empty//FTP文件名称,或,FTP文件目录名称
                    , str_line = System.String.Empty;//FTP文件流字符串
                System.Collections.Generic.List<System.String> list_dic_or_file = new System.Collections.Generic.List<System.String>();//文件集合
                ftp_web_request = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(str_ftp_absolute_path));//初始Uri实例
                ftp_web_request.Credentials = new System.Net.NetworkCredential(str_ftp_user, str_ftp_pass);//设置与FTP服务器通信的凭证
                ftp_web_request.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//设置向FTP发送获取文件的详细列表的指令
                web_response = ftp_web_request.GetResponse();//获取FTP响应回来的文件流
                stream_reader = new System.IO.StreamReader(web_response.GetResponseStream(), System.Text.Encoding.UTF8);//响应设置为Internal资源的数据流
                str_line = stream_reader.ReadLine();//从当前流读取一行字符并将数据作为字符串返回
                while (str_line != null)
                {
                    if (str_line.Contains("<DIR>"))
                    {//文件夹

                    }
                    else if (!str_line.Contains("<DIR>"))
                    {
                        str_line = str_line.Replace(" ", "").Replace("-","").Replace(":","");
                        str_line = RemoveNumber(str_line);
                        str_dir_or_file = str_line.Substring(2).Trim();
                        strLsFilePath = strLsFilePath + "," + str_dir_or_file;
                    }
                    list_dic_or_file.Add(str_dir_or_file);
                    str_line = stream_reader.ReadLine();//从当前流读取下一行字符并将数据作为字符串返回
                } 
                web_response.Close();
                stream_reader.Close();
                dic_result["state"] = "1";
                dic_result["msg"] = "成功";
                dic_result["list"] = list_dic_or_file;
            }
            catch (Exception ex)
            { 
                dic_result["state"] = "0";
                dic_result["msg"] = ex.Message;
                dic_result["list"] = null;
            }
            return dic_result;
        }
        public static string RemoveNumber(string key)
        {
            return System.Text.RegularExpressions.Regex.Replace(key, @"\d", "");
        }

注意事项:
仅支持读取文件名不包含 阿拉伯数字=: 的文件;
以上感谢观看
作者: 龙文浩 C#工程师+Java工程师

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值