C#底层库--文件操作类(文件重命名、目录移动、字节流转换)

系列文章

C#底层库–程序日志记录类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/124187709

C#底层库–MySQLBuilder脚本构建类(select、insert、update、in、带条件的SQL自动生成)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/129179216

C#底层库–MySQL数据库访问操作辅助类(推荐阅读)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126886379

C#底层库–XML配置参数读写辅助类(推荐阅读)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/129175304

C#底层库–获取文件版本和MD5值
本文链接:https://blog.csdn.net/youcheng_ge/article/details/112513871

C#底层库–文件操作类(文件重命名、目录移动、字节流转换)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126887161

C#底层库–Excel操作帮助库(可读加密Excel表格)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126887445

C#底层库–随机数生成器
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126888812

C#底层库–RegexHelper正则表达式辅助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/109745286

C#底层库–CSV和DataTable相互转换
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128804367

C#底层库–Image图片操作类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128805298

C#底层库–JSON使用教程_详细(序列化、反序列化、转DataTable)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128805705

C#底层库–cookie使用教程
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128816347

C#底层库–Session操作辅助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128817096

C#底层库–Image图片操作类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128805298

C#底层库–数据库类型与程序类型转换器
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128817610

C#底层库–StringExtension字符串扩展类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/129520428

C#底层库–自定义进制转换器(可去除特殊字符,非Convert.ToString方式)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/130444724


前言

本专栏为【底层库】,主要介绍编程过程中 通用函数。我们将这些通用固化的源码,进行重写、封装、拓展,再进行单元测试、集成测试、beta测试,最终形成通用化模板,这里我们称为“底层库”。

作为研发人员的你,并不需要花大量时间,研究“底层库”的含义,及“底层库”的实现方法。你只需要几行调用代码,就可以解决项目上碰到的难题。而底层库使用方法,本专栏均有详细介绍,也有项目应用场景。

底层库已实现功能:MySQL脚本构建器、MySQL数据库访问操作、参数配置文件读写、加解密算法、日志记录、HTTP通信、Socket通信、API前后端交互、邮件发送、文件操作、配置参数存储、Excel导入导出、CSV和DataTable转换、压缩解压、自动编号、Session操作等。

本专栏会持续更新,不断优化【底层库】,大家有任何问题,可以私信我。本专栏之间关联性较强(我会使用到某些底层库,某些文章可能忽略介绍),如果您对本专栏感兴趣,欢迎关注,我将带你用最简洁的代码,实现最复杂的功能。
在这里插入图片描述

一、底层库介绍

C#底层库–文件操作类(删除目录文件、复制文件到指定目录)

功能包含:
1、文件 转换为 字节数组,文件流 转化为 字节数组,
2、获取指定目录中、指定拓展名,文件的绝对路径
3、复制目录下文件到指定目录,目录转移,路径合并,删除指定目录文件。
4、文件重命名,文件移动
5、以UTF8编码,在指定路径写文件

二、底层库源码

创建类FileHelper.cs

using System;
using System.IO;
using System.Text;

namespace Geyc_Utils.FileOperate
{
    /// <summary>
    /// 文件操作类
    /// 创建人:gyc
    /// 创建时间:2022-03-31
    /// 功能:
    /// 1、文件 转换为 字节数组,文件流 转化为 字节数组,
    /// 2、获取指定目录中、指定拓展名,文件的绝对路径
    /// 3、复制目录下文件到指定目录,目录转移,路径合并,删除指定目录文件。
    /// 4、文件重命名,文件移动
    /// 5、以UTF8编码,在指定路径写文件
    /// 
    /// 说明:使用过程中发现错误,请联系作者修改 https://blog.csdn.net/youcheng_ge
    /// </summary>
    public class FileHelper
    {


        /// <summary>
        /// 构造函数
        /// </summary>
        public FileHelper() { }


        /// <summary>
        /// 文件 转换为 字节数组
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>字节数组</returns>
        public byte[] GetBinaryFile(string filename)
        {
            if (File.Exists(filename))
            {
                FileStream Fsm = null;
                try
                {
                    Fsm = File.OpenRead(filename);
                    return this.ConvertStreamToByteBuffer(Fsm);
                }
                catch (Exception)
                {
                    return new byte[0];
                }
                finally
                {
                    Fsm.Close();
                }
            }
            else
            {
                return new byte[0];
            }
        }


        /// <summary>
        /// 文件流 转化为 字节数组
        /// </summary>
        /// <param name="theStream">文件流</param>
        /// <returns>字节数组</returns>
        public byte[] ConvertStreamToByteBuffer(Stream theStream)
        {
            int bi;
            MemoryStream tempStream = new MemoryStream();
            try
            {
                while ((bi = theStream.ReadByte()) != -1)
                {
                    tempStream.WriteByte(((byte)bi));
                }
                return tempStream.ToArray();
            }
            catch (Exception)
            {
                return new byte[0];
            }
            finally
            {
                tempStream.Close();
            }
        }


        /// <summary>
        /// 路径合并
        /// </summary>
        /// <param name="srcPath"></param>
        /// <param name="destPath"></param>
        /// <returns></returns>
        public string PathCombine(string srcPath, string destPath)
        {
            return Path.Combine(srcPath, destPath);
        }


        /// <summary>
        /// 获取指定目录中、指定拓展名,文件的绝对路径
        /// </summary>
        /// <param name="a_dirName">目录</param>
        /// <param name="a_fileName">文件名</param>
        /// <param name="a_Extension">拓展名</param>
        /// <returns></returns>
        public string FindFilePath(string a_dirName, string a_fileName, string a_Extension)
        {
            string a_strFileAbsolutelyPath = "";
            DirectoryInfo l_dirInfo = new DirectoryInfo(a_dirName);
            //返回目录中所有文件
            FileInfo[] l_files = l_dirInfo.GetFiles();
            foreach (FileInfo info in l_files)
            {
                if (info.Name.Contains(a_fileName) && info.Extension == a_Extension)
                {
                    a_strFileAbsolutelyPath = info.FullName;
                    return a_strFileAbsolutelyPath;
                }
            }

            //返回目录中所有子目录
            DirectoryInfo[] l_childsDir = l_dirInfo.GetDirectories();
            if (l_childsDir.Length >= 0)
            {
                foreach (DirectoryInfo dirInfo in l_childsDir)
                {
                    a_strFileAbsolutelyPath = FindFilePath(dirInfo.FullName, a_fileName, a_Extension);
                    return a_strFileAbsolutelyPath;
                }
            }
            return a_strFileAbsolutelyPath;
        }


        /// <summary>
        /// 复制目录下文件到指定的目录
        /// </summary>
        /// <param name="sourceDir">源目录</param>
        /// <param name="destDir">目标目录</param>
        private void CopyDirectory(string sourceDir, string destDir)
        {
            DirectoryInfo srcDirectory = new DirectoryInfo(sourceDir);
            DirectoryInfo destDirectory = new DirectoryInfo(destDir);

            if (destDirectory.FullName.StartsWith(srcDirectory.FullName, StringComparison.CurrentCultureIgnoreCase))
            {
                throw new Exception("无法将复制文件到子目录,检查文件是否被占用!");
            }

            if (!srcDirectory.Exists)
            {
                throw new Exception("源目录不存在,请检查!");
            }

            if (!destDirectory.Exists)
            {
                destDirectory.Create();
            }

            FileInfo[] files = srcDirectory.GetFiles();

            for (int i = 0; i < files.Length; i++)
            {
                CopyFile(files[i].FullName, destDirectory.FullName);
            }

            //获取子目录
            DirectoryInfo[] dirs = srcDirectory.GetDirectories();
            for (int j = 0; j < dirs.Length; j++)
            {
                //使用递归调用,获取子目录中文件
                CopyDirectory(dirs[j].FullName, Path.Combine(destDirectory.FullName, dirs[j].Name));
            }
        }


        /// <summary>
        /// 复制文件
        /// </summary>
        /// <param name="sourceFile">源文件名</param>
        /// <param name="destDir">目标路径</param>
        public void CopyFile(string sourceFile, string destDir)
        {
            DirectoryInfo destDirectory = new DirectoryInfo(destDir);
            string l_strFileName = Path.GetFileName(sourceFile);
            if (!File.Exists(sourceFile))
            {
                return;
            }

            if (!destDirectory.Exists)
            {
                destDirectory.Create();
            }
            File.Copy(sourceFile, Path.Combine(destDirectory.FullName, l_strFileName), true);
        }


        /// <summary>
        /// 文件重命名,文件移动
        /// </summary>
        /// <param name="sourceFile">源文件</param>
        /// <param name="destFile">目标文件</param>
        public void RenameFile(string sourceFile, string destFile)
        {
            if (!File.Exists(sourceFile))
            {
                return;
            }

            string l_strDirectoryName = Path.GetDirectoryName(destFile);
            DirectoryInfo destDirectory = new DirectoryInfo(l_strDirectoryName);

            if (!destDirectory.Exists)
            {
                destDirectory.Create();
            }

            File.Move(sourceFile, destFile);
        }


        /// <summary>
        /// 删除指定目录及其所有文件
        /// </summary>
        /// <param name="a_strPath">目录</param>
        public void DeleteDirectory(string a_strPath)
        {
            try
            {
                //去除文件夹和子文件的只读\隐藏属性
                DirectoryInfo fileInfo = new DirectoryInfo(a_strPath);
                fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
                //去除文件的只读\隐藏属性
                File.SetAttributes(a_strPath, FileAttributes.Normal);

                //判断文件夹是否还存在
                if (Directory.Exists(a_strPath))
                {
                    foreach (string f in Directory.GetFileSystemEntries(a_strPath))
                    {
                        if (File.Exists(f))
                        {
                            File.Delete(f);
                        }
                        else
                        {
                            DeleteDirectory(f);
                        }
                    }

                    //删除空文件夹
                    Directory.Delete(a_strPath);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


        /// <summary>
        /// 以UTF8编码,在指定路径写文件
        /// </summary>
        /// <param name="a_fileText">文件内容</param>
        /// <param name="a_FileFullPath">绝对路径</param>
        public void FileWrite(string a_fileText, string a_FileFullPath)
        {
            string dir = Path.GetDirectoryName(a_FileFullPath);

            if (!Directory.Exists(dir)) //目录不存在创建目录
            {
                Directory.CreateDirectory(dir);
            }

            using (FileStream fs = new FileStream(a_FileFullPath, FileMode.Create))
            {
                using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                {
                    sw.Write(a_fileText);
                }
            }
        }


    }
}

三、调用方法

需要先实例化类,采用点方法调用,代码如下:

	FileHelper fileHelper = new FileHelper();
	//删除代码目录
	fileHelper .DelDirSub(PrintInfoTemp.LocalPath);

四、项目案例

我做了一个【代码检查工具】,程序员SVN提交的代码,服务器自动下载代码,并检查完代码后。使用本底层库,删除指定目录下,所有SVN下载代码。
本案例有点复杂,仅供参考,大家可以根据自己项目情况调用。

		/// <summary>
		/// 代码信息收集
		/// </summary>
		/// <param name="a_AssemblyInfo"></param>
		/// <param name="a_strZJConnnection"></param>
		/// <param name="a_param1"></param>
		/// <param name="a_param2"></param>
		/// <param name="a_param3"></param>
		/// <param name="a_bSuccess"></param>
		/// <param name="a_strMsgError"></param>
		public static void CodeInfoCollection(AssemblyInfo a_AssemblyInfo,string a_strZJConnnection,
		                                      string a_param1,string a_param2,string a_param3,
		                                      out bool a_bSuccess,out string a_strMsgError)
		{
			MakeSQLHelper m_MakeSQLHelper = new MakeSQLHelper();
			a_bSuccess = true;
			a_strMsgError = "";
			
			if(a_AssemblyInfo.SourceCodePath==""
			   ||a_AssemblyInfo.CVSPath==""
			   ||a_AssemblyInfo.CVSRootPath=="")
			{
				a_bSuccess = false;
				a_strMsgError = "CVS代码路径为空!";
				return;
			}
			
			if(a_AssemblyInfo.WorkDir == "")
			{
				a_bSuccess = false;
				a_strMsgError = "CVS工作目录为空!";
				return;
			}
			
			if(a_AssemblyInfo.CVSExePath=="")
			{
				a_bSuccess = false;
				a_strMsgError = "CVS安装程序为空!";
				return;
			}
			
			PrintInfo PrintInfoTemp = new PrintInfo();
			PrintInfoTemp.SystemNo = a_AssemblyInfo.SystemNo;
			PrintInfoTemp.AssemblyNo = a_AssemblyInfo.AssemblyNo;
			PrintInfoTemp.CVSPath = a_AssemblyInfo.CVSPath;
			PrintInfoTemp.CVSRootPath = a_AssemblyInfo.CVSRootPath;
			PrintInfoTemp.SourceCodePath = a_AssemblyInfo.SourceCodePath;
			PrintInfoTemp.CVSExePath = a_AssemblyInfo.CVSExePath;
			PrintInfoTemp.CVSUser = a_AssemblyInfo.CVSUser;
			PrintInfoTemp.CVSPsw = a_AssemblyInfo.CVSPsw;
			PrintInfoTemp.WorkDir = a_AssemblyInfo.WorkDir;
			PrintInfoTemp.CVSCmdPath = PrintInfoTemp.SourceCodePath.Replace(@"I:\CVSCode\W4\", "");
			PrintInfoTemp.CVSCmd = string.Format(Const.ct_strCVSCMD, PrintInfoTemp.CVSUser, PrintInfoTemp.CVSPsw, PrintInfoTemp.CVSCmdPath);
			
			#region CVS代码下载
			CVSHelper m_CVSHelper = new CVSHelper();
			//1、CVS代码授权
			if(a_bSuccess)
			{
				string l_strCVSMsg = "";
				if(m_CVSHelper.CVSSaveTakeData(PrintInfoTemp.CVSRootPath,PrintInfoTemp.CVSPath,PrintInfoTemp.CVSUser,
				                               PrintInfoTemp.AssemblyNo,out l_strCVSMsg))
				{
					a_bSuccess = true;
					a_strMsgError = l_strCVSMsg;
				}
				else
				{
					a_bSuccess = false;
					a_strMsgError = l_strCVSMsg;
				}
			}
			
			//2、代码下载
			if(a_bSuccess)
			{
				string l_strCVSMsg = "";
				string l_strTempPath = PrintInfoTemp.SourceCodePath.Replace(@"I:\CVSCode\W4\", "");
				string l_strCmd = string.Format(Const.ct_strCVSCMD, PrintInfoTemp.CVSUser, PrintInfoTemp.CVSPsw, l_strTempPath);
				PrintInfoTemp.LocalPath = Path.Combine(PrintInfoTemp.WorkDir, l_strTempPath);
				if(m_CVSHelper.CVSCodeDown(PrintInfoTemp.CVSExePath,l_strCmd,PrintInfoTemp.WorkDir,out l_strCVSMsg) )
				{
					//检查是否更新成功
					if(!Directory.Exists(PrintInfoTemp.LocalPath))
					{
						a_bSuccess = false;
						a_strMsgError = "CVS代码下载为空!";
					}
				}
				else
				{
					m_CVSHelper.p_ErrorDataReceived(null,null);
					FileHelper.DelDirSub(PrintInfoTemp.LocalPath);
					a_bSuccess = false;
					a_strMsgError = "CVS代码下载异常,"+l_strCVSMsg;
				}
			}
			#endregion
			
			#region 2、加载文件MainController
			string[] l_ArrayCodeContent = null;
			string l_strCodeContent = "";//代码内容
			string l_strFileAbsolutelyPath = "";
			if(a_bSuccess)
			{
				l_strFileAbsolutelyPath = FileHelper.FindFilePath(PrintInfoTemp.LocalPath,"MainController",".cs");
				if(File.Exists( l_strFileAbsolutelyPath))
				{
					l_ArrayCodeContent = File.ReadAllLines(l_strFileAbsolutelyPath);
					l_strCodeContent = File.ReadAllText(l_strFileAbsolutelyPath);
				}
				else
				{
					a_bSuccess = false;
					a_strMsgError = "MainController.cs文件不存在!";
				}
			}
			#endregion
			
			#region 数据集定义
			List<T_client_assembly_dataset_define> list_assembly_dataset = new List<T_client_assembly_dataset_define>();
			List<T_client_assembly_dataset_field> list_assembly_dataset_field = new List<T_client_assembly_dataset_field>();
			list_assembly_dataset.Clear();
			list_assembly_dataset_field.Clear();
			
			if(a_bSuccess)
			{
				Dictionary<string,string> dic_cdsEntity = new Dictionary<string,string>();
				
				Regex reg_Entity = new Regex(@"(cds\S*Entity)(?!\(\))",RegexOptions.IgnoreCase);
				MatchCollection matches = reg_Entity.Matches(l_strCodeContent );
				foreach(Match item in matches)
				{
					if(dic_cdsEntity.ContainsKey(item.Value)==false)
					{
						dic_cdsEntity.Add(item.Value,item.Value);
					}
				}
				
				foreach(var item in dic_cdsEntity)
				{
					T_client_assembly_dataset_define assembly_dataset = new T_client_assembly_dataset_define();
					assembly_dataset.system_no = PrintInfoTemp.SystemNo;
					assembly_dataset.assembly_no = PrintInfoTemp.AssemblyNo;
					assembly_dataset.dataset_define = item.Value;
					list_assembly_dataset.Add(assembly_dataset);
				}
				
				foreach(var itemEntity in dic_cdsEntity)
				{
					string l_strCdsFileName = itemEntity.Value.Replace("Entity","");
					l_strFileAbsolutelyPath = FileHelper.FindFilePath(PrintInfoTemp.LocalPath,l_strCdsFileName,".dsxml");
					
					if(File.Exists(l_strFileAbsolutelyPath) && l_strFileAbsolutelyPath!="")
					{
						List<DataSetField>list_DataSetField = new List<DataSetField>();
						list_DataSetField = PrintDataLib.GetDataSetByPath(l_strFileAbsolutelyPath);
						if(list_DataSetField!=null && list_DataSetField.Count>0)
						{
							foreach(DataSetField Field in list_DataSetField)
							{
								T_client_assembly_dataset_field l_dataset_field = new T_client_assembly_dataset_field();
								l_dataset_field.system_no = PrintInfoTemp.SystemNo;
								l_dataset_field.assembly_no = PrintInfoTemp.AssemblyNo;
								l_dataset_field.dataset_define = itemEntity.Value;
								l_dataset_field.field_name = Field.field_name;
								l_dataset_field.db_name = Field.db_name;
								l_dataset_field.table_name = Field.table_name;
								l_dataset_field.field_type = Field.field_type;
								l_dataset_field.col_name = Field.col_name;
								l_dataset_field.data_type = Field.data_type;
								l_dataset_field.caption = Field.caption;
								l_dataset_field.col_len = Field.col_len;
								l_dataset_field.field_note = Field.field_note;
								l_dataset_field.is_pk = Field.is_pk;
								list_assembly_dataset_field.Add(l_dataset_field);
							}
						}
					}
					else
					{
						a_bSuccess = false;
						a_strMsgError = "未找到数据集文件"+l_strCdsFileName+".dsxml";
						break;
					}
				}
			}
			
			
			if(a_bSuccess)
			{
				try
				{
					string l_strSqlAll = "";
					string l_strSqlDel = string.Format(Const.ct_strDelAssemblyDatasetDefine,PrintInfoTemp.SystemNo,PrintInfoTemp.AssemblyNo);
					string l_strInsert = "";
					if(list_assembly_dataset!=null && list_assembly_dataset.Count>0)
					{
						l_strInsert=m_MakeSQLHelper.CreateInsertSQLBuilder("T_client_assembly_dataset_define",list_assembly_dataset);
					}
					l_strSqlAll = l_strSqlDel+"\r\n"+l_strInsert+"\r\n";
					DBOperate.DBInsertAndUpdate(a_strZJConnnection,l_strSqlAll);
				}
				catch(Exception ex)
				{
					a_bSuccess = false;
					a_strMsgError = "保存数据集定义异常:"+ex.Message;
				}
			}
			
			if(a_bSuccess)
			{
				try
				{
					string l_strSqlAll = "";
					string l_strSqlDel = string.Format(Const.ct_strDelAssemblyDatasetfield,PrintInfoTemp.SystemNo,PrintInfoTemp.AssemblyNo);
					string l_strInsert = "";
					if(list_assembly_dataset_field!=null && list_assembly_dataset_field.Count>0)
					{
						l_strInsert=m_MakeSQLHelper.CreateInsertSQLBuilder("T_client_assembly_dataset_field",list_assembly_dataset_field);
					}
					l_strSqlAll = l_strSqlDel+"\r\n"+l_strInsert+"\r\n";
					DBOperate.DBInsertAndUpdate(a_strZJConnnection,l_strSqlAll);
				}
				catch(Exception ex)
				{
					a_bSuccess = false;
					a_strMsgError = "保存数据集字段异常:"+ex.Message;
				}
			}
			#endregion
			
			if(a_bSuccess)
			{
				//大循环,遍历整个代码行,把所有的 PrintCall.Print 都找到
				for(int OutCodeNum = 0; OutCodeNum<l_ArrayCodeContent.Length;OutCodeNum++ )
				{
					string l_strPrintCall = "";
					bool l_bMatch = false;
					
					//循环,找到一个  PrintCall.Print  把 代码 复制到 l_strPrintCall
					for(int IncodeNum=OutCodeNum;IncodeNum<l_ArrayCodeContent.Length;IncodeNum++)
					{
						string l_oneline = PrintDataLib.RemoveSpace(l_ArrayCodeContent[IncodeNum]);
						if(l_oneline.Contains("//")) continue;
						
						//3.1 匹配PrintCall语句
						Regex reg = new Regex(@"PrintCall.Print\((.*?)",RegexOptions.IgnoreCase);
						Match match = reg.Match(l_oneline);
						if(match.Success)//匹配到
						{
							l_bMatch = true;
						}
						
						if(l_bMatch)//匹配到
						{
							if(l_strPrintCall.Contains(";"))
							{
								PrintInfoTemp.PrintCallRowNum = IncodeNum;//行数
								PrintInfoTemp.PrintCall = l_strPrintCall;//PrintCall行
								OutCodeNum = IncodeNum + 1;  //这个代表 大循环应该从 找到的下一行继续找下一个  PrintCall行
								
								//3.2 获取打印方法,反向逆读取代码行
								bool l_bFindMethodIsSucee = false;
								for(int j=PrintInfoTemp.PrintCallRowNum;j>0;j--)
								{
									string l_strLastRead = PrintDataLib.RemoveSpace(l_ArrayCodeContent[j]);//行号
									
									if(l_strLastRead.Contains("publicvoid"))
									{
										l_bFindMethodIsSucee = true;
										PrintInfoTemp.Method = PrintDataLib.SubstringSingle(l_strLastRead,"publicvoid","(");
										break;
									}
									else if(l_strLastRead.Contains("publicbool"))
									{
										l_bFindMethodIsSucee = true;
										PrintInfoTemp.Method = PrintDataLib.SubstringSingle(l_strLastRead,"publicbool","(");
										break;
									}
								}
								
								if(!l_bFindMethodIsSucee)
								{
									a_bSuccess = false;
									a_strMsgError = "未找到printcall语句!";
									continue;
								}
								
								//3.3 获取打印类型
								List<T_client_assembly_print_dataset> m_listprint_dataset = new List<T_client_assembly_print_dataset>();
								List<T_client_assembly_print_dataset_field> m_listprint_dataset_field = new List<T_client_assembly_print_dataset_field>();
								
								m_listprint_dataset.Clear();
								m_listprint_dataset_field.Clear();
								
								string l_strPrint = PrintDataLib.SubstringSingle(PrintInfoTemp.PrintCall,"PrintCall.Print(",");");
								string l_BillTypeVar = "";//打印类型变量
								string[] l_CdsMasterVar;//数据集
								string[] l_DataTableVar;//表
								try
								{
									PrintDataLib.SplitPrintParm(l_strPrint,out l_BillTypeVar,out l_CdsMasterVar,out l_DataTableVar);
								}
								catch(Exception)
								{
									a_bSuccess = false;
									a_strMsgError = "printcall语句语法解析失败:"+PrintInfoTemp.PrintCall;
									continue;
								}
								
								PrintInfoTemp.BillTypePar = PrintDataLib.GetFunParbyName(l_ArrayCodeContent,l_BillTypeVar);
								PrintInfoTemp.CdsMasterVar = l_CdsMasterVar;//数据集
								PrintInfoTemp.DataTableVar = l_DataTableVar;//数据表
								
								//3.4 数据集
								m_listprint_dataset.Clear();
								for(int l_intDatasetSN = 0;l_intDatasetSN<PrintInfoTemp.CdsMasterVar.Length;l_intDatasetSN++)
								{
									T_client_assembly_print_dataset l_print_dataset = new T_client_assembly_print_dataset();
									l_print_dataset.system_no = PrintInfoTemp.SystemNo;
									l_print_dataset.assembly_no = PrintInfoTemp.AssemblyNo;
									l_print_dataset.print_method = PrintInfoTemp.Method;
									l_print_dataset.order_sn = l_intDatasetSN+1;
									l_print_dataset.dataset_fun_par = PrintDataLib.GetFunParbyName(l_ArrayCodeContent,PrintInfoTemp.CdsMasterVar[l_intDatasetSN]);
									l_print_dataset.dataset_name = PrintInfoTemp.CdsMasterVar[l_intDatasetSN];
									m_listprint_dataset.Add(l_print_dataset);
								}
								
								//3.5 数据集字段
								bool l_bIsFindXml = false;//是否匹配到
								m_listprint_dataset_field.Clear();
								List<DataSetField> list_DataSetField;
								for(int l_intDatasetSN = 0;l_intDatasetSN<PrintInfoTemp.DataTableVar.Length;l_intDatasetSN++)
								{
									string l_strCdsFileName = PrintDataLib.GetdsxmlFileNameByDataTable(l_ArrayCodeContent,PrintInfoTemp.DataTableVar[l_intDatasetSN]);
									
									l_strFileAbsolutelyPath = FileHelper.FindFilePath(PrintInfoTemp.LocalPath,l_strCdsFileName,".dsxml");
									
									if(File.Exists(l_strFileAbsolutelyPath) && l_strFileAbsolutelyPath!="")
									{
										l_bIsFindXml = true;
										list_DataSetField = new List<DataSetField>();
										list_DataSetField = PrintDataLib.GetDataSetByPath(l_strFileAbsolutelyPath);
										if(list_DataSetField!=null && list_DataSetField.Count>0)
										{
											foreach(DataSetField Field in list_DataSetField)
											{
												T_client_assembly_print_dataset_field l_print_dataset_field = new T_client_assembly_print_dataset_field();
												l_print_dataset_field.system_no = PrintInfoTemp.SystemNo;
												l_print_dataset_field.assembly_no = PrintInfoTemp.AssemblyNo;
												l_print_dataset_field.print_method = PrintInfoTemp.Method;
												l_print_dataset_field.order_sn = l_intDatasetSN+1;
												l_print_dataset_field.field_name = Field.field_name;
												l_print_dataset_field.db_name = Field.db_name;
												l_print_dataset_field.table_name = Field.table_name;
												l_print_dataset_field.field_type = Field.field_type;
												l_print_dataset_field.col_name = Field.col_name;
												l_print_dataset_field.data_type = Field.data_type;
												l_print_dataset_field.caption = Field.caption;
												l_print_dataset_field.col_len = Field.col_len;
												l_print_dataset_field.field_note = Field.field_note;
												l_print_dataset_field.is_pk = Field.is_pk;
												m_listprint_dataset_field.Add(l_print_dataset_field);
											}
										}
									}
									else
									{
										a_bSuccess = false;
										a_strMsgError = "未找到数据集文件"+l_strCdsFileName+".dsxml";
										break;
									}
								}
								
								//未找到XML文件,终止执行
								if(!l_bIsFindXml)
								{
									break;
								}
								
								//打印方法构造
								T_client_assembly_print_method l_print_method = new T_client_assembly_print_method();
								List<T_client_assembly_print_method> m_listprint_method = new List<T_client_assembly_print_method>();
								m_listprint_method.Clear();
								l_print_method = new T_client_assembly_print_method();
								l_print_method.assembly_no = PrintInfoTemp.AssemblyNo;
								l_print_method.system_no = PrintInfoTemp.SystemNo;
								l_print_method.print_method = PrintInfoTemp.Method;
								l_print_method.print_type_fun_par = PrintInfoTemp.BillTypePar;
								m_listprint_method.Add(l_print_method);
								
								string l_strSqlAll = "";
								string l_strSqlDel = "";
								string l_strInsert = "";
								
								if(m_listprint_method.Count>0)
								{
									try
									{
										l_strSqlAll = "";
										l_strSqlDel = string.Format(Const.ct_strDelmethod,PrintInfoTemp.SystemNo,PrintInfoTemp.AssemblyNo,PrintInfoTemp.Method);
										l_strInsert = "";
										l_strInsert=m_MakeSQLHelper.CreateInsertSQLBuilder("T_client_assembly_print_method",m_listprint_method);
										l_strSqlAll = l_strSqlDel+"\r\n"+l_strInsert+"\r\n";
										DBOperate.DBInsertAndUpdate(a_strZJConnnection,l_strSqlAll);
									}
									catch(Exception ex)
									{
										l_strPrintCall = "";
										l_bMatch = false;//是否匹配到
										a_bSuccess = false;
										a_strMsgError = "插入打印方法表异常:"+ex.Message;
										return;
									}
								}
								
								//T_client_assembly_print_dataset
								if(m_listprint_dataset.Count>0)
								{
									try
									{
										l_strSqlAll = "";
										l_strSqlDel = string.Format(Const.ct_strDeldataset,PrintInfoTemp.SystemNo,PrintInfoTemp.AssemblyNo,PrintInfoTemp.Method);
										l_strInsert = m_MakeSQLHelper.CreateInsertSQLBuilder("T_client_assembly_print_dataset",m_listprint_dataset);
										l_strSqlAll = l_strSqlDel+"\r\n"+l_strInsert+"\r\n";
										DBOperate.DBInsertAndUpdate(a_strZJConnnection,l_strSqlAll);
									}
									catch(Exception ex)
									{
										l_strPrintCall = "";
										l_bMatch = false;
										a_bSuccess = false;
										a_strMsgError = "插入打印数据集异常:"+ex.Message;
										return;
									}
								}
								
								//T_client_assembly_print_dataset_field
								if(m_listprint_dataset_field.Count>0)
								{
									try
									{
										l_strSqlAll = "";
										l_strSqlDel = string.Format(Const.ct_strDeldataset_field,PrintInfoTemp.SystemNo,PrintInfoTemp.AssemblyNo,PrintInfoTemp.Method);
										l_strInsert = m_MakeSQLHelper.CreateInsertSQLBuilder("T_client_assembly_print_dataset_field",m_listprint_dataset_field);
										l_strSqlAll = l_strSqlDel+"\r\n"+l_strInsert+"\r\n";
										DBOperate.DBInsertAndUpdate(a_strZJConnnection,l_strSqlAll);
									}
									catch(Exception ex)
									{
										l_strPrintCall = "";
										l_bMatch = false;//是否匹配到
										a_bSuccess = false;
										a_strMsgError = "插入打印数据集字段异常:"+ex.Message;
										return;
									}
								}
								
								break;
							}
							else
							{
								l_strPrintCall += l_oneline;
							}
						}
						
					}
					//结束大循环
					if(!l_bMatch)
					{
						break;
					}
				}
			}
			
			
			#region Cost常量
			List<T_client_assembly_constant> list_assembly_constant = new List<T_client_assembly_constant>();
			list_assembly_constant.Clear();
			CompilerResults cr  = null;
			
			if(a_bSuccess)
			{
				string l_strConstFilePath = FileHelper.FindFilePath(PrintInfoTemp.LocalPath,"Const",".cs");
				if(!File.Exists( l_strConstFilePath) || l_strConstFilePath=="")
				{
					return;
				}

				// 1.CSharpCodePrivoder
				CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider();

				// 2.ICodeComplier
				ICodeCompiler objICodeCompiler = objCSharpCodePrivoder.CreateCompiler();
				// 3.CompilerParameters
				CompilerParameters objCompilerParameters = new CompilerParameters();
				objCompilerParameters.ReferencedAssemblies.Add("System.dll");
				objCompilerParameters.GenerateExecutable = false;
				objCompilerParameters.GenerateInMemory = true;

				// 4.CompilerResults
				string l_strText = File.ReadAllText(l_strConstFilePath);
				cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters,l_strText);
				
				if(cr.Errors.HasErrors)
				{
					string l_strZJName = "";
					foreach (CompilerError err in cr.Errors)
					{
						l_strZJName += err.ErrorText+"、";
					}
					a_bSuccess = false;
					a_strMsgError = "Const单元动态加载失败,引用未知组件"+l_strZJName;
				}
			}
			
			//反射
			if(a_bSuccess)
			{
				string l_strNameSpace = "";
				Regex reg_namespace = new Regex(@"(?<=namespace).*",RegexOptions.IgnoreCase);
				MatchCollection matches_namespace = reg_namespace.Matches(l_strCodeContent );
				foreach(Match item in matches_namespace)
				{
					l_strNameSpace = PrintDataLib.RemoveSpace(item.Value);
				}
				
				if(l_strNameSpace=="")
				{
					a_bSuccess = false;
					a_strMsgError = "获取命名空间名失败";
					return;
				}
				
				//5、CompiledAssembly
				try
				{
					Assembly objAssembly = cr.CompiledAssembly;
					Type t = objAssembly.GetType( l_strNameSpace+".Const");
					FieldInfo[] fis=t.GetFields();  // 注意,这里不能有任何选项,否则将无法获取到const常量
					
					foreach (var fieldInfo in fis)
					{
						T_client_assembly_constant assembly_constant = new T_client_assembly_constant();
						assembly_constant.constant_guid = Guid.NewGuid().ToString();
						assembly_constant.system_no = PrintInfoTemp.SystemNo;
						assembly_constant.assembly_no = PrintInfoTemp.AssemblyNo;
						assembly_constant.const_name = fieldInfo.Name;
						assembly_constant.const_value = fieldInfo.GetRawConstantValue().ToString();
						list_assembly_constant.Add(assembly_constant);
					}
				}
				catch(Exception)
				{
					a_bSuccess = false;
					a_strMsgError = "Const单元代码反射解析失败,不能转换为Type类型!";
				}
			}
			
			
			if(a_bSuccess)
			{
				try
				{
					string l_strSqlAll = "";
					string l_strSqlDel = string.Format(Const.ct_strDelConstant,PrintInfoTemp.SystemNo,PrintInfoTemp.AssemblyNo);
					string l_strInsert = "";
					if(list_assembly_constant!=null && list_assembly_constant.Count>0)
					{
						l_strInsert=m_MakeSQLHelper.CreateInsertSQLBuilder("T_client_assembly_constant",list_assembly_constant);
					}
					l_strSqlAll = l_strSqlDel+"\r\n"+l_strInsert+"\r\n";
					DBOperate.DBInsertAndUpdate(a_strZJConnnection,l_strSqlAll);
				}
				catch(Exception ex)
				{
					a_bSuccess = false;
					a_strMsgError = "保存常量数据异常:"+ex.Message;
				}
			}
			#endregion
			
			#region 词汇引用(word_table、simple_code)
			List<T_client_assembly_word> l_list_assembly_word = new List<T_client_assembly_word>();
			l_list_assembly_word.Clear();
			
			if(a_bSuccess)
			{
				m_listReadFile.Clear();
				FindFiles(PrintInfoTemp.LocalPath,".cs");
				
				if(m_listReadFile==null && m_listReadFile.Count==0)
				{
					a_bSuccess = false;
					a_strMsgError = "项目中不存在*.cs文件,无法解析词汇引用!";
				}
			}

			
			if(a_bSuccess)
			{
				foreach(string l_strFile in m_listReadFile)//文件列表
				{
					string l_strFileName = System.IO.Path.GetFileName(l_strFile);
					string l_strWord = "";
					string l_strType = "";
					
					l_strCodeContent = "";
					
					if(File.Exists( l_strFile))
					{
						l_strCodeContent = File.ReadAllText(l_strFile);
						Dictionary<string,string> dic_Word = new Dictionary<string,string>();
						
						Regex reg_Entity = new Regex(@"(?<=Register\()([^;]*)(?=\))",RegexOptions.IgnoreCase);
						MatchCollection matches = reg_Entity.Matches(l_strCodeContent );
						
						foreach(Match item in matches)
						{
							if(dic_Word.ContainsKey(item.Value)==false)
							{
								dic_Word.Add(item.Value,item.Value);
							}
						}
						
						foreach(var item in dic_Word)
						{
							PrintDataLib.GetWordKind(item.Key,out l_strWord,out l_strType);
							T_client_assembly_word assembly_word = new T_client_assembly_word();
							assembly_word.word_guid = Guid.NewGuid().ToString();
							assembly_word.system_no = PrintInfoTemp.SystemNo;
							assembly_word.assembly_no = PrintInfoTemp.AssemblyNo;
							assembly_word.words_kind = l_strWord;
							assembly_word.words_type = l_strType;
							l_list_assembly_word.Add(assembly_word);
						}
					}
					else
					{
						a_bSuccess = false;
						a_strMsgError = "文件路径不存在:"+l_strFile;
						break;
					}
				}
			}
			
			if(a_bSuccess)
			{
				try
				{
					string l_strSqlAll = "";
					string l_strSqlDel = string.Format(Const.ct_strDelWord,PrintInfoTemp.SystemNo,PrintInfoTemp.AssemblyNo);
					string l_strInsert = "";
					if(l_list_assembly_word!=null && l_list_assembly_word.Count>0)
					{
						l_strInsert=m_MakeSQLHelper.CreateInsertSQLBuilder("T_client_assembly_word",l_list_assembly_word);
					}
					l_strSqlAll = l_strSqlDel+"\r\n"+l_strInsert+"\r\n";
					DBOperate.DBInsertAndUpdate(a_strZJConnnection,l_strSqlAll);
				}
				catch(Exception ex)
				{
					a_bSuccess = false;
					a_strMsgError = "保存词汇引用数据异常:"+ex.Message;
				}
			}
			#endregion
			
			#region 表格控件对象
			List<T_client_assembly_grid_controls_views> list_controls_views = new List<T_client_assembly_grid_controls_views>();
			List<T_client_assembly_grid_controls_columns> list_controls_columns = new List<T_client_assembly_grid_controls_columns>();
			list_controls_views.Clear();
			list_controls_columns.Clear();
			
			if(a_bSuccess)
			{
				string l_strSqlDel = string.Format(Const.ct_strDelControlsViews,PrintInfoTemp.SystemNo,PrintInfoTemp.AssemblyNo);
				DBOperate.DBInsertAndUpdate(a_strZJConnnection,l_strSqlDel);
				l_strSqlDel = string.Format(Const.ct_strDelControlsColumns,PrintInfoTemp.SystemNo,PrintInfoTemp.AssemblyNo);
				DBOperate.DBInsertAndUpdate(a_strZJConnnection,l_strSqlDel);
				
				foreach(string l_strFile in m_listReadFile)
				{
					string l_strFileName = System.IO.Path.GetFileName(l_strFile);
					
					if(l_strFile.Contains("DataSet") )//排除数据集
					{
						continue;
					}
					
					if(!l_strFileName.Contains("Designer")  )
					{
						continue;
					}
					
					if(File.Exists(l_strFile))
					{
						list_controls_views.Clear();
						list_controls_columns.Clear();
						
						GridControlsOpera l_GridControls = new GridControlsOpera();
						l_GridControls.AnalysisDBGrid(l_strFile,PrintInfoTemp.SystemNo,PrintInfoTemp.AssemblyNo,
						                              out list_controls_views,out list_controls_columns);
						try
						{
							string l_strInsert = "";
							if(list_controls_views!=null && list_controls_views.Count>0)
							{
								l_strInsert=m_MakeSQLHelper.CreateInsertSQLBuilder("T_client_assembly_grid_controls_views",list_controls_views);
								DBOperate.DBInsertAndUpdate(a_strZJConnnection,l_strInsert);
							}
						}
						catch(Exception ex)
						{
							a_bSuccess = false;
							a_strMsgError = "保存表控件异常:"+ex.Message;
						}
						
						try
						{
							string l_strInsert = "";
							if(list_controls_columns!=null && list_controls_columns.Count>0)
							{
								l_strInsert=m_MakeSQLHelper.CreateInsertSQLBuilder("T_client_assembly_grid_controls_columns",list_controls_columns);
								DBOperate.DBInsertAndUpdate(a_strZJConnnection,l_strInsert);
							}
						}
						catch(Exception ex)
						{
							a_bSuccess = false;
							a_strMsgError = "保存表格列控件异常:"+ex.Message;
						}
					}
				}
			}
			#endregion
			
			#region 数据权限
			List<T_client_assembly_data_power> l_list_data_power = new List<T_client_assembly_data_power>();
			l_list_data_power.Clear();
			if(a_bSuccess)
			{
				foreach(string l_strFile in m_listReadFile)//文件列表
				{
					string l_strFileName = System.IO.Path.GetFileName(l_strFile);
					string l_strFun = "";
					string l_strParam = "";
					
					if(l_strFileName.Contains("Designer") )
					{
						continue;
					}
					
					l_strCodeContent = "";
					
					if(File.Exists( l_strFile))
					{
						DataPowerOpera l_DataPower = new DataPowerOpera();
						
						Dictionary<string,string> dic_Power = new Dictionary<string,string>();
						dic_Power = l_DataPower.GetBizHandler(l_strFile);
						
						foreach(var item in dic_Power)
						{
							l_DataPower.GetDataPower(item.Key,out l_strFun,out l_strParam);
							T_client_assembly_data_power data_power = new T_client_assembly_data_power();
							data_power.power_guid = Guid.NewGuid().ToString();
							data_power.system_no = PrintInfoTemp.SystemNo;
							data_power.assembly_no = PrintInfoTemp.AssemblyNo;
							data_power.power_fun_name = l_strFun;
							data_power.param_text = l_strParam;
							l_list_data_power.Add(data_power);
						}
					}
					else
					{
						a_bSuccess = false;
						a_strMsgError = "文件路径不存在:"+l_strFile;
						break;
					}
				}
			}
			
			if(a_bSuccess)
			{
				try
				{
					string l_strSqlAll = "";
					string l_strSqlDel = string.Format(Const.ct_strDelPower,PrintInfoTemp.SystemNo,PrintInfoTemp.AssemblyNo);
					string l_strInsert = "";
					if(l_list_data_power!=null && l_list_data_power.Count>0)
					{
						l_strInsert=m_MakeSQLHelper.CreateInsertSQLBuilder("T_client_assembly_data_power",l_list_data_power);
					}
					l_strSqlAll = l_strSqlDel+"\r\n"+l_strInsert+"\r\n";
					DBOperate.DBInsertAndUpdate(a_strZJConnnection,l_strSqlAll);
				}
				catch(Exception ex)
				{
					a_bSuccess = false;
					a_strMsgError = "保存数据权限异常:"+ex.Message;
				}
			}
			#endregion
			
			
			//删除代码目录
			FileHelper.DelDirSub(PrintInfoTemp.LocalPath);
		}
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花北城

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值