代码改变世界

获取文件--->修改内容 --> 保存 --> 关闭

2020-03-10 15:58  石吴玉  阅读(163)  评论(0编辑  收藏  举报
       public static FileMgr_Rep UploadLamborFrontEndWeb_IndexContent_Files(int MasterID, MasterLogoUrlSettingInfo ContentFillConent, int type, string StatisticalCode)
        {
            FileMgr_Rep ReqInfo = new FileMgr_Rep();
            //涉及对服务器上文件读写,可能会抛出异常
            try
            {
                //获取文件地址 
                string path = AppDomain.CurrentDomain.BaseDirectory;
                //测试时获取到的发布后的地址格式:D:\\LamborPublic\\LamborBackOfficeBLServicePublic\\
                //获取项目根目录的上一级目录(需修改文件夹目录于之同级)
                int index = path.LastIndexOf("\\");
                path = path.Substring(0, index);
                index = path.LastIndexOf("\\");
                path = path.Substring(0, index);
                //生成指定站长的文件路径(本地测试需要构造测试环境———>在调用此方法的项目根目录同级添加Lambor.GameFrontEnd.MasterID文件夹,内部录入Index.html文件)
                path = path + "\\Lambor.GameFrontEnd." + MasterID + "\\index.html";
                //获取文件内容
                Stream myStream = new FileStream(path, FileMode.Open,FileAccess.ReadWrite);
                StreamReader myStreamReader = new StreamReader(myStream, Encoding.UTF8);
                string strhtml = myStreamReader.ReadToEnd();
                //正则
                string pattern = string.Empty;
                //修改站长前端网站的key,title, description
                if (type == 1)
                {
                    //标记添加块位置
                    int headIndex = -1;
                    //C# 使用正则匹配html的三个标签(存在则替换内容,不存在则新增内容)
                    //匹配修改title标签的正则表达式
                    if (ContentFillConent.UpdateType == 1)
                    {
                        if (strhtml.IndexOf("<title>") > -1)
                        {
                            pattern = @"<title>(?<str>.*?)</title>";
                            strhtml = Regex.Replace(strhtml, pattern, "<title>" + ContentFillConent.Title + "</title>");
                        }
                        else
                        {
                            //把数据添加到</head>之前
                            headIndex = strhtml.IndexOf("</head>");
                            strhtml = strhtml.Insert(headIndex, "<title>" + ContentFillConent.Title + "</title>");
                        }
                    }
         }
myStream.Seek(0, SeekOrigin.Begin); myStream.SetLength(0); StreamWriter sw = new StreamWriter(myStream, Encoding.UTF8); sw.Write(strhtml); sw.Flush(); sw.Close(); myStream.Close(); ReqInfo.Ret = (int)ErrorRetType.SUCCESS; return ReqInfo; } catch (Exception ex) { ReqInfo.Ret = (int)ErrorRetType.COMM_FAIL; //寫入操作Log(对前端html5文件的操作) var TitleInfoList = new List<string>(); TitleInfoList.Add(MasterID.ToString()); BackOffice.Utility.OperatorLogUtility.WriteOperatorLog_Update(MasterID, MasterID, LamborDataModelLib.Model.Defines.ModifyType.UploadLamborFrontEndWeb_IndexContent, TitleInfoList); return ReqInfo; } }