Пример #1
0
        private static void Reset(string filePath, string content, bool keepBak)
        {
            var fileName = $"{EnvUtil.GetBaseDirectory()}/{filePath}";
            var file     = new FileInfo(fileName);

            try
            {
                if (keepBak && file.Exists)
                {
                    var bakFile = new FileInfo(fileName + ".bak");
                    if (bakFile.Exists)
                    {
                        bakFile.Delete();
                    }
                    File.Move(fileName, fileName + ".bak");
                }

                var data = Encoding.UTF8.GetBytes(content);

                using (var fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    fs.SetLength(0);
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                    fs.Dispose();
                }
            }
            catch
            {
            }
        }
Пример #2
0
        static BasePluginHost()
        {
            plugins = new Dictionary <IPlugin, PluginPackAttribute>();

            string appDirectory = EnvUtil.GetBaseDirectory();

            string pluginDirectory = String.Concat(
                appDirectory,
                PluginConfig.PLUGIN_DIRECTORY);

            //清空日志
            string pluginTmpDirectory = String.Concat(appDirectory, PluginConfig.PLUGIN_TMP_DIRECTORY);

            if (!Directory.Exists(pluginTmpDirectory))
            {
                Directory.CreateDirectory(pluginTmpDirectory);
            }
            Log = new FileLogger(String.Format("{0}plugin_load.log",
                                               pluginTmpDirectory), false);
            Log.Truncate();

            if (Directory.Exists(pluginDirectory))
            {
                LoadPluginFromDirectory(pluginDirectory);
            }
            else
            {
                Directory.CreateDirectory(pluginDirectory).Create();
            }

            //加载程序集的.so文件
            loadFromAppDomain();
        }
Пример #3
0
        public void CreateView_POST()
        {
            var tplname = string.Format("templates/{0}/{1}.{2}",
                                        CurrentSite.Tpl,
                                        Request.Form("name"),
                                        Request.Form("type") == "1" ? "part.html" : "html");

            var tplPath = string.Format("{0}/{1}",
                                        EnvUtil.GetBaseDirectory(),
                                        tplname);

            if (File.Exists(tplPath))
            {
                Response.WriteAsync("文件已经存在!");
            }
            else
            {
                try
                {
                    //global::System.IO.Directory.CreateDirectory(tplPath).Create();   //创建目录
                    File.Create(tplPath).Dispose(); //创建文件

                    Cms.Template.Reload();          //重新注册模板

                    Response.WriteAsync(tplname);
                }
                catch (Exception e)
                {
                    // Response.Write(e.Message);
                    Response.WriteAsync("无权限创建文件,请设置视图目录(templates)可写权限!");
                }
            }
        }
Пример #4
0
        /// <summary>
        /// 升级更新
        /// </summary>
        private static int ApplyUpgrade_Core()
        {
            DirectoryInfo libDir = new DirectoryInfo(EnvUtil.GetBaseDirectory() + "/bin/");

            //初始化设置权限
            // message = "bin目录无法写入更新文件,请修改权限!";
            //return -1;
            if ((libDir.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
            {
                libDir.Attributes = libDir.Attributes & ~FileAttributes.ReadOnly;
            }
            try
            {
                //如果升级成功,执行操作
                if (OnUpgrade != null)
                {
                    OnUpgrade();
                }
            }
            catch
            {
            }

            return(1);
        }
Пример #5
0
        /// <summary>
        /// 获取插件包的信息
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static IEnumerable <PluginPackAttribute> GetPluginPackInfo(string fileName)
        {
            var tempDir = String.Concat(EnvUtil.GetBaseDirectory() + "/", PluginConfig.PLUGIN_TMP_DIRECTORY, "tmp/");

            if (Directory.Exists(tempDir))
            {
                Directory.Delete(tempDir, true);
            }
            Directory.CreateDirectory(tempDir).Create();

            var dir = new DirectoryInfo(tempDir);

            ZipUtility.DecompressFile(tempDir, fileName, false);

            Assembly ass;

            string[] multExt = PluginConfig.GetFilePartterns();
            foreach (String ext in multExt)
            {
                var files = dir.GetFiles(ext);
                foreach (FileInfo f in files)
                {
                    ass = Assembly.Load(File.ReadAllBytes(f.FullName));

                    var attbs = ass.GetCustomAttributes(typeof(PluginPackAttribute), false);
                    foreach (object attb in attbs)
                    {
                        if (attb is PluginPackAttribute)
                        {
                            yield return((PluginPackAttribute)attb);
                        }
                    }
                }
            }
        }
Пример #6
0
        public void CreateView_POST()
        {
            var tplName = $"templates/{CurrentSite.Tpl}/{Request.Form("name")}.html";
            var tplPath = $"{EnvUtil.GetBaseDirectory()}/{tplName}";

            if (File.Exists(tplPath))
            {
                Response.WriteAsync("文件已经存在!");
            }
            else
            {
                try
                {
                    //global::System.IO.Directory.CreateDirectory(tplPath).Create();   //创建目录
                    File.Create(tplPath).Dispose(); //创建文件
                    Cms.Template.Reload();          //重新注册模板
                    Response.WriteAsync(tplName);
                }
                catch (Exception e)
                {
                    // Response.Write(e.Message);
                    Response.WriteAsync("无权限创建文件,请设置视图目录(templates)可写权限!");
                }
            }
        }
Пример #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="workerIndent"></param>
        public PluginPackAttribute(string workerIndent)
        {
            this.WorkIndent = workerIndent;
            bool isChanged = false;
            var  dirPath   = Path.Combine(EnvUtil.GetBaseDirectory(),
                                          PluginConfig.PLUGIN_DIRECTORY,
                                          workerIndent,
                                          "/");

            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath).Create();
            }

            settings = new SettingFile(string.Concat(dirPath, "plugin.config"));

            if (!settings.Contains(PluginSettingKeys.State))
            {
                settings.Set(PluginSettingKeys.State, "Normal");
                isChanged = true;
            }
            if (!settings.Contains(PluginSettingKeys.OverrideUrlIndent))
            {
                settings.Set(PluginSettingKeys.OverrideUrlIndent, "");
                isChanged = true;
            }

            if (isChanged)
            {
                settings.Flush();
            }
        }
Пример #8
0
        /// <summary>
        /// 实例化数据库访问对象
        /// </summary>
        /// <param name="type"></param>
        /// <param name="connectionString"></param>
        public DataBaseAccess(DataBaseType type, string connectionString)
        {
            if (connectionString.IndexOf("$ROOT$") != -1)
            {
                connectionString = connectionString.Replace("$ROOT$",
                                                            EnvUtil.GetBaseDirectory());
            }

            this.DbType = type;

            switch (type)
            {
            case DataBaseType.OLEDB:
                dbDialect = new OleDbFactory(connectionString);
                break;

            case DataBaseType.SQLite:
                dbDialect = new SQLiteFactory(connectionString);
                break;

            case DataBaseType.MonoSQLite:
                throw new Exception("not implement on .net standard");

            //    dbDialect = new MonoSQLiteFactory(connectionString);
            case DataBaseType.SQLServer:
                dbDialect = new SqlServerFactory(connectionString);
                break;

            case DataBaseType.MySQL:
                dbDialect = new MySqlFactory(connectionString);
                break;
            }
        }
Пример #9
0
        /// <summary>
        /// 删除文件或目录
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="file"></param>
        /// <param name="isDir"></param>
        /// <returns></returns>
        internal static bool Delete(string dir, string file, bool isDir)
        {
            dir = Regex.Replace(dir, "^(\\/)*([\\S\\s]+)(\\/)$", "$2");
            var path = EnvUtil.GetBaseDirectory() + dir + file;

            if (isDir)
            {
                //如果为系统文件,则返回false
                foreach (var s in SysIntArray)
                {
                    if (string.CompareOrdinal(s, file) == 0)
                    {
                        return(false);
                    }
                }
                Directory.Delete(path + "/"); //目录下有文件,不能删除
            }
            else
            {
                //如果为系统文件,则返回false
                foreach (var s in SysIntArray)
                {
                    if (string.CompareOrdinal(s, file.Replace("\\", "")) == 0)
                    {
                        return(false);
                    }
                }

                File.Delete(path);
            }

            return(true);
        }
Пример #10
0
        /// <summary>
        /// 编辑模板
        /// </summary>
        public void Edit()
        {
            string tpl = Request.Query("tpl");

            if (string.IsNullOrEmpty(tpl))
            {
                tpl = CurrentSite.Tpl;
            }
            var sb = new StringBuilder();

            var dir = new DirectoryInfo($"{EnvUtil.GetBaseDirectory()}/templates/{tpl}/");

            if (!dir.Exists)
            {
                Response.Redirect(Request.GetPath() + "?module=template&action=templates", false);
                return;
            }

            EachClass.WalkTemplateFiles(dir, sb, tpl);

            RenderTemplate(ResourceMap.GetPageContent(ManagementPage.Template_Edit), new
            {
                tplfiles = sb.ToString(),
                tpl      = tpl
            });
        }
Пример #11
0
        private static void ResolveAspNet(string resolveFullDir)
        {
            AppDomain domain = AppDomain.CurrentDomain;

            if (String.IsNullOrEmpty(resolveFullDir))
            {
                resolveFullDir = EnvUtil.GetBaseDirectory() + FwCtx.Variables.AssemblyPath;
            }

            //
            //设为隐藏目录
            //
            domain.AssemblyResolve += delegate(object sender, ResolveEventArgs args)
            {
                string filePath = String.Concat(resolveFullDir, args.Name.Split(',')[0], ".dll");

                //File.WriteAllText(directory+DateTime.Now.Millisecond.ToString()+".txt",args.Name+"//"+filePath);

                if (!File.Exists(filePath))
                {
                    return(null);
                }
                else
                {
                    return(Assembly.Load(File.ReadAllBytes(filePath)));
                }
            };
        }
Пример #12
0
        internal static bool IsDebug()
        {
            bool isDebug = false;

            try
            {
                using (StreamReader fs = new StreamReader($"{EnvUtil.GetBaseDirectory()}Web.config"))
                {
                    string content;
                    Regex  reg = new Regex("<compilation[^(debug)]+debug=\"([^\"]+)\"", RegexOptions.IgnoreCase);
                    while ((content = fs.ReadLine()) != null)
                    {
                        if (reg.IsMatch(content))
                        {
                            Match m = reg.Match(content);
                            if (m.Groups[1].Value == "true")
                            {
                                isDebug = true;
                            }
                        }
                    }
                    fs.Dispose();
                }
            }
            catch (IOException exc)
            {
            }
            return(isDebug);
        }
Пример #13
0
        /// <summary>
        /// 获取插件的图标
        /// </summary>
        /// <param name="workerIndent"></param>
        /// <returns></returns>
        public static byte[] GetPluginIcon(string workerIndent, int width, int height, string defaultIconPath)
        {
            string icon      = null;
            var    iconExist = false;

            byte[] data;

            Iterate((p, a) =>
            {
                if (String.Compare(a.WorkIndent, workerIndent, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    icon = String.Format("{0}/{1}{2}/{3}",
                                         EnvUtil.GetBaseDirectory(),
                                         PluginConfig.PLUGIN_DIRECTORY,
                                         workerIndent, a.Icon);
                }
            });

            if (!String.IsNullOrEmpty(icon))
            {
                iconExist = File.Exists(icon);
            }

resetIcon:
            if (!iconExist)
            {
                icon = defaultIconPath;
            }

            var bit = (Bitmap)null;

            try
            {
                using (bit = new Bitmap(icon))
                {
                    var ms = GraphicsHelper.MakeThumbnail(bit, ImageSizeMode.AutoSuit, width, height, null);
                    data = ms.ToArray();
                    ms.Dispose();
                    bit.Dispose();
                }
            }
            catch
            {
                iconExist = false;
                goto resetIcon;
            }
            finally
            {
                if (bit != null)
                {
                    bit.Dispose();
                }
            }

            return(data);
        }
Пример #14
0
        public static string GetJson(string dir_abs_path)
        {
            var dir = new DirectoryInfo(Path.Combine(EnvUtil.GetBaseDirectory(), dir_abs_path));

            if (!dir.Exists)
            {
                return(ReturnError($"目录:{dir_abs_path}不存在!"));
            }
            return(GetJson(dir, dir_abs_path == "/"));
        }
Пример #15
0
 protected void saveLog(string str)
 {
     using (
         System.IO.StreamWriter sr =
             new System.IO.StreamWriter(EnvUtil.GetBaseDirectory() + "collection.log", true))
     {
         sr.WriteLine(str);
         sr.Flush();
         sr.Dispose();
     }
 }
Пример #16
0
 public DbAccess(DataBaseType dbType, string connectionString, bool sqlTrace)
 {
     _dbType           = dbType;
     _connectionString = connectionString;
     _sqlTrace         = sqlTrace;
     dbAccess          = new DataBaseAccess(_dbType, _connectionString);
     if (sqlTrace)
     {
         _fileLogger = new FileLogger(EnvUtil.GetBaseDirectory() + "/tmp/sql_profile.txt");
         _fileLogger.Truncate();
         dbAccess.Use(profileTrace);
     }
 }
Пример #17
0
        public HttpTagsHandler(string configPath)
        {
            this.configPath = configPath;

            //获取配置文件的路径
            if (String.IsNullOrEmpty(configPath))
            {
                this.configPath = EnvUtil.GetBaseDirectory() + request.GetParameter("config");
            }

            //创建标签管理器对象
            Tags = new TagsManager(configPath);
        }
Пример #18
0
        private void Thumbnal_Test()
        {
            int    imgHeight = 480, imgWidth = 600;
            string file      = "/1.jpg";
            string waterPath = "";
            string rootPath  = EnvUtil.GetBaseDirectory();

            Bitmap img = new Bitmap(rootPath + file);
            int    width, height;

            if (img.Width > img.Height)
            {
                width  = imgWidth;
                height = imgHeight;
            }
            else
            {
                width  = imgHeight;
                height = imgWidth;
            }

            byte[] data = DrawBySize(img, ImageSizeMode.CustomSize, width, height, ImageFormat.Jpeg, 90L,
                                     50L, null);
            img.Dispose();


            MemoryStream ms1 = new MemoryStream(data);

            img = new Bitmap(ms1);

            Image water = new Bitmap(waterPath);


            data = MakeWatermarkImage(
                img,
                water,
                WatermarkPosition.Middle
                );


            ms1.Dispose();
            img.Dispose();

            FileStream   fs = File.OpenWrite(rootPath + "/1_1.jpg");
            BinaryWriter w  = new BinaryWriter(fs);

            w.Write(data);
            w.Flush();
            fs.Flush();
            fs.Dispose();
        }
Пример #19
0
        /// <summary>
        /// 获取模板
        /// </summary>
        /// <returns></returns>
        public static IDictionary <string, string> GetTemplates()
        {
            IDictionary <string, string> dict = new Dictionary <string, string>();
            var tplRootPath = $"{EnvUtil.GetBaseDirectory()}/templates/";
            var dir         = new DirectoryInfo(tplRootPath);

            var dirs = dir.GetDirectories();
            var tpls = new string[dirs.Length];

            if (dir.Exists)
            {
                var i = -1;
                foreach (var d in dirs)
                {
                    if ((d.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
                    {
                        tpls[++i] = d.Name;
                    }
                }
            }

            SettingFile sf;
            string      tplConfigFile,
                        tplName;

            foreach (var key in tpls)
            {
                tplName = key;

                tplConfigFile = string.Format("{0}{1}/tpl.conf", tplRootPath, key);
                if (File.Exists(tplConfigFile))
                {
                    sf = new SettingFile(tplConfigFile);
                    if (sf.Contains("name"))
                    {
                        tplName = sf["name"];
                    }
                    //if (sf.Contains("thumbnail"))
                    //{
                    //    tplThumbnail = sf["thumbnail"];
                    //}
                }

                if (!string.IsNullOrEmpty(key))
                {
                    dict.Add(key, tplName);
                }
            }

            return(dict);
        }
Пример #20
0
        /// <summary>
        /// 注册模板
        /// </summary>
        public void Register(string directory)
        {
            var dir = new DirectoryInfo(EnvUtil.GetBaseDirectory() + "/" + directory);

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException("模版文件夹不存在!");
            }
            // 添加到目录数组,用于重新加载模板
            if (!this.directories.Contains(directory))
            {
                this.directories.Add(directory);
            }
            //注册模板
            RegisterTemplates(dir, this._options.Names);
        }
Пример #21
0
        /// <summary>
        /// 设置目录权限
        /// </summary>
        /// <param name="dirPath"></param>
        public void SetDirCanWrite(string dirPath)
        {
            var dir = new DirectoryInfo(EnvUtil.GetBaseDirectory() + dirPath);

            if (dir.Exists)
            {
                if ((dir.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                {
                    dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
                }
            }
            else
            {
                Directory.CreateDirectory(dir.FullName).Create();
            }
        }
Пример #22
0
        /// <summary>
        /// 重命名
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="file"></param>
        /// <param name="newFile"></param>
        /// <param name="isDir"></param>
        /// <returns></returns>
        internal static bool Rename(string dir, string file, string newFile, bool isDir)
        {
            dir = Regex.Replace(dir, "^(\\/)*([\\S\\s]+)(\\/)$", "$2");

            var path    = Path.Combine(EnvUtil.GetBaseDirectory(), dir, file);
            var newPath = Path.Combine(EnvUtil.GetBaseDirectory(), dir, newFile);

            if (isDir)
            {
                Directory.Move(path + "/", newPath + "/");
            }
            else
            {
                File.Move(path, newPath);
            }
            return(true);
        }
Пример #23
0
        /// <summary>
        /// 升级指定的模板包(-1:获取包失败,-2:已经安装,1:安装成功)
        /// </summary>
        public static int InstallTemplate(string tplName, string url)
        {
            string        tplRootPath = EnvUtil.GetBaseDirectory() + "/templates/";
            MemoryStream  ms;
            IArchive      archive;
            DirectoryInfo dir;

            if (!url.ToUpper().StartsWith("HTTP://"))
            {
                url = GetUpdateUrl(url);
            }
            byte[] zipData = DownloadFile(url, null);

            if (zipData == null)
            {
                return(-1);
            }

            dir = new DirectoryInfo(tplRootPath); // + tplName);  模板包括模板文件名

            //模板不存在,则解压
            if (!dir.Exists)
            {
                ms = new MemoryStream(zipData);

                archive = ArchiveFactory.Open(ms);

                foreach (IArchiveEntry entry in archive.Entries)
                {
                    if (!entry.IsDirectory)
                    {
                        entry.WriteToDirectory(dir.FullName, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                    }
                }

                archive.Dispose();
                ms.Dispose();
            }
            else
            {
                return(-2);
            }

            return(1);
        }
Пример #24
0
        /// <summary>
        /// 编辑文件
        /// </summary>
        public string EditFile()
        {
            string path = Request.Query("path");
            string content,
                   bakinfo;

            FileInfo file, bakfile;

            file    = new FileInfo(EnvUtil.GetBaseDirectory() + path);
            bakfile = new FileInfo(EnvUtil.GetBaseDirectory() + Helper.GetBackupFilePath(path));


            if (!file.Exists)
            {
                return("文件不存在!");
            }
            else
            {
                if (bakfile.Exists)
                {
                    bakinfo = string.Format(@"上次修改时间日期:{0:yyyy-MM-dd HH:mm:ss}&nbsp;
                                <a style=""margin-right:20px"" href=""javascript:;"" onclick=""process('restore')"">还原</a>",
                                            bakfile.LastWriteTime);
                }
                else
                {
                    bakinfo = "";
                }
            }

            var sr = new StreamReader(file.FullName);

            content = sr.ReadToEnd();
            sr.Dispose();


            content = content.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;");
            ViewData["raw_content"] = content;
            ViewData["bakinfo"]     = bakinfo;
            ViewData["file"]        = path;
            ViewData["path"]        = path;

            return(RequireTemplate(CompressHtml(ResourceMap.GetPageContent(ManagementPage.Template_EditFile))));
        }
Пример #25
0
        public static void SaveErrorLog(Exception exception)
        {
            lock (ErrorFilePath)
            {
                var req          = HttpHosting.Context.Request;
                var path         = req.GetPath();
                var query        = req.GetQueryString();
                var PathAndQuery = path + query;
                req.TryGetHeader("Referer", out var referer);
                if (!File.Exists(ErrorFilePath))
                {
                    var dir = EnvUtil.GetBaseDirectory() + "/tmp/logs";
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    File.Create(ErrorFilePath).Close();
                }

                HttpHosting.Context.Response.WriteAsync(File.Exists(ErrorFilePath).ToString());
                using (var fs = new FileStream(ErrorFilePath, FileMode.Append, FileAccess.Write))
                {
                    var sw = new StreamWriter(fs);
                    var sb = new StringBuilder();

                    sb.Append("---------------------------------------------------------------------\r\n")
                    .Append("[错误]:IP:")
                    .Append(HttpHosting.Context.RemoteAddress())
                    .Append("\t时间:").Append(DateTime.Now.ToString())
                    .Append("\r\n[信息]:").Append(exception.Message)
                    .Append("\r\n[路径]:").Append(PathAndQuery)
                    .Append("  -> 来源:").Append(referer)
                    .Append("\r\n[堆栈]:").Append(exception.StackTrace)
                    .Append("\r\n\r\n");

                    sw.Write(sb.ToString());

                    sw.Flush();
                    sw.Dispose();
                    fs.Dispose();
                }
            }
        }
Пример #26
0
 /// <summary>
 /// 设置目录隐藏
 /// </summary>
 /// <param name="dirPath"></param>
 public static void SetDirHidden(string dirPath)
 {
     if (!FwCtx.Mono())
     {
         DirectoryInfo dir = new DirectoryInfo($"{EnvUtil.GetBaseDirectory()}/{dirPath}");
         if (!dir.Exists)
         {
             Directory.CreateDirectory(dir.FullName).Create();
             dir.Attributes = dir.Attributes & FileAttributes.Hidden;
         }
         else
         {
             if ((dir.Attributes & FileAttributes.Hidden) != FileAttributes.ReadOnly)
             {
                 dir.Attributes = dir.Attributes & FileAttributes.Hidden;
             }
         }
     }
 }
Пример #27
0
        /// <summary>
        /// 编辑模板
        /// </summary>
        public void Edit()
        {
            var sb = new StringBuilder();

            var cssDir = new DirectoryInfo($"{EnvUtil.GetBaseDirectory()}/style/");
            var cfgDir = new DirectoryInfo($"{EnvUtil.GetBaseDirectory()}/config/");

            //sb.Append("<optgroup label=\"样式表\">");
            //EachClass.EachFiles(cssDir, sb, "style",".css", true);
            sb.Append("</optgroup><optgroup label=\"设置文件\">");
            EachClass.EachFiles(cfgDir, sb, "config", ".xml ; .ini ; .conf", true);
            sb.Append("</optgroup>");

            RenderTemplate(ResourceMap.GetPageContent(ManagementPage.File_SelectEdit), new
            {
                files  = sb.ToString(),
                systpl = CurrentSite.Tpl
            });
        }
Пример #28
0
 /// <summary>
 /// 设置目录隐藏
 /// </summary>
 /// <param name="dirPath"></param>
 public void SetDirHidden(string dirPath)
 {
     if (!Cms.RunAtMono)
     {
         var dir = new DirectoryInfo(EnvUtil.GetBaseDirectory() + dirPath);
         if (!dir.Exists)
         {
             Directory.CreateDirectory(dir.FullName).Create();
             dir.Attributes = dir.Attributes & FileAttributes.Hidden;
         }
         else
         {
             if ((dir.Attributes & FileAttributes.Hidden) != FileAttributes.ReadOnly)
             {
                 dir.Attributes = dir.Attributes & FileAttributes.Hidden;
             }
         }
     }
 }
Пример #29
0
        /// <summary>
        /// 注册模板
        /// </summary>
        public void Register(string directory, TemplateResolveHandler handler = null)
        {
            var dir = new DirectoryInfo(EnvUtil.GetBaseDirectory() + directory);

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException("模版文件夹不存在!");
            }
            // 添加到目录数组,用于重新加载模板
            if (!this._directories.Contains(directory))
            {
                this._directories.Add(directory);
            }
            // 重置模板缓存
            this.ResetCaches();
            this._resolveHandler = handler;
            //注册模板
            RegisterTemplates(dir, this._options, handler);
        }
Пример #30
0
        /// <summary>
        /// 上传
        /// </summary>
        /// <returns>异步则返回进程ID,同步返回上传文件的路径</returns>
        public string Upload()
        {
            HttpRequest request = (HttpHosting.Context.RawContext() as HttpContext).Request;
            String      baseDir = EnvUtil.GetBaseDirectory();

            string[] process = request.Form["upload_process"][0].Split('|');
            string   processID = process[1], field = process[0];

            var postedFile = request.Form.Files[field];

            if (postedFile == null)
            {
                return(null);
            }
            string fileExt = postedFile.FileName.Substring(postedFile.
                                                           FileName.LastIndexOf('.') + 1); //扩展名

            InitUplDirectory(baseDir, this._saveAbsoluteDir);
            this._fileInfo = new UploadFileInfo
            {
                Id            = processID,
                ContentLength = postedFile.Length,
                FilePath      = $"{this._saveAbsoluteDir}{this._fileName}.{fileExt}"
            };
            String targetPath = baseDir + this._fileInfo.FilePath;

            if (!this._autoRename && File.Exists(targetPath))
            {
                throw new IOException("文件已存在");
            }
            // 自动将重复的名称命名
            int i = 0;

            while (File.Exists(targetPath))
            {
                i++;
                this._fileInfo.FilePath = $"{this._saveAbsoluteDir}{this._fileName}_{i.ToString()}.{fileExt}";
                targetPath = baseDir + this._fileInfo.FilePath;
            }
            this.SaveStream(postedFile.OpenReadStream(), targetPath);
            return(_fileInfo.FilePath);
        }