DeleteFile() public static method

删除文件
public static DeleteFile ( string pathName ) : bool
pathName string
return bool
Example #1
0
        private static void DownFinished()
        {
            string sLocalFile = DownloadState.Parameter.LocalFile;
            var    blocklist  = DownloadState.BlockList;

            if (File.Exists(sLocalFile))
            {
                FileUtil.DeleteFile(sLocalFile);
            }
            using (var writer = new FileStream(sLocalFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
            {
                foreach (Blocks item in blocklist)
                {
                    if (!File.Exists(item.FilePath))
                    {
                        continue;
                    }
                    var buffer = new byte[3 * 1024 * 1024];
                    using (var reader = new FileStream(item.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        int readlength = 0;
                        while ((readlength = reader.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            writer.Write(buffer, 0, readlength);
                            writer.Flush();
                        }
                        reader.Close();
                    }
                }
                writer.Close();
            }
        }
    /// <summary>
    /// 基础
    /// </summary>
    public void UIForBase()
    {
        GUILayout.BeginHorizontal();

        if (EditorUI.GUIButton("刷新所有资源", 200))
        {
            InitData();
            HandleForAllAssetChange();
        }
        if (EditorUI.GUIButton("保存所有数据", 200))
        {
            string saveData = JsonUtil.ToJsonByNet(addressableSaveData);
            FileUtil.CreateTextFile(pathSaveData, saveDataFileName, saveData);
            EditorUtil.RefreshAsset();
        }
        if (EditorUI.GUIButton("清除所有数据", 200))
        {
            if (EditorUI.GUIDialog("确认", "是否清除所有数据"))
            {
                FileUtil.DeleteFile($"{pathSaveData}/{saveDataFileName}");
                InitData();
                EditorUtil.RefreshAsset();
            }
        }
        GUILayout.EndHorizontal();
    }
        public override bool SaveAddNew()
        {
            TablesInfo info = new TablesInfo();

            SetInfo(info);

            try
            {
                #region 新增数据
                XmlHelper xmltableshelper = new XmlHelper(@"XML\tables.xml");
                xmltableshelper.Replace(string.Format("datatype/dataitem/item[@gid=\"{0}\"]/basicdatapath", info.Gid), info.BasicdataPath);
                xmltableshelper.Save();

                if (FileUtil.FileIsExist(info.BasicdataPath))
                {
                    FileUtil.DeleteFile(info.BasicdataPath);
                }

                string tablesdataDetailModel = "<?xml version=\"1.0\" encoding=\"utf-8\"?><datatype><dataitem></dataitem></datatype>";
                FileUtil.AppendText(info.BasicdataPath, tablesdataDetailModel, System.Text.Encoding.UTF8);

                //ID = info.GUID;
                strItemName = cbbItemName.SelectedText;
                return(true);

                #endregion
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(FrmEditBasicDataItemName));
                MessageDxUtil.ShowError(ex.Message);
            }
            return(false);
        }
Example #4
0
        /// <summary>
        /// 查找不适用文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFindNotSetFile_Click(object sender, EventArgs e)
        {
            string path = txtPath.Text.Trim();

            if (string.IsNullOrEmpty(path))
            {
                path = FileDialogHelper.OpenDir();
            }

            if (!DirectoryUtil.IsExistDirectory(path))
            {
                MessageDxUtil.ShowTips("文件路径不可用");
                return;
            }

            string recordFileName = "\\" + "不适用文件.txt";

            if (FileUtil.FileIsExist(path + recordFileName))
            {
                FileUtil.DeleteFile(path + recordFileName);
            }
            FileUtil.CreateFile(path + recordFileName);

            string[] allFiles = DirectoryUtil.GetAllFileNames(path);
            foreach (var file in allFiles)
            {
                FileInfo fileInfo = new FileInfo(file);
                if (fileInfo.Name.Contains("不适用"))
                {
                    FileUtil.AppendText(path + recordFileName, string.Format("{0}\t\t\t{1}\r\n", fileInfo.Name, fileInfo.FullName), Encoding.UTF8);
                }
            }

            MessageDxUtil.ShowTips("操作完成");
        }
Example #5
0
        public virtual void TestThatCssIsReleasedAfterConversion()
        {
            // TODO update after DEVSIX-3205 is fixed
            String dirName        = "CssIsReleased/";
            String htmlFileName   = "cssIsReleased.html";
            String cssFileName    = "cssIsReleased.css";
            String sourceHtmlFile = sourceFolder + dirName + htmlFileName;
            String sourceCssFile  = sourceFolder + dirName + cssFileName;
            String workDir        = destinationFolder + dirName;

            CreateDestinationFolder(workDir);
            String targetPdfFile   = workDir + "target.pdf";
            String workDirHtmlFile = workDir + htmlFileName;
            String workDirCssFile  = workDir + cssFileName;

            File.Copy(Path.Combine(sourceHtmlFile), Path.Combine(workDirHtmlFile));
            File.Copy(Path.Combine(sourceCssFile), Path.Combine(workDirCssFile));
            ConverterProperties properties = new ConverterProperties().SetBaseUri(workDir);

            HtmlConverter.ConvertToPdf(new FileInfo(workDirHtmlFile), new FileInfo(targetPdfFile), properties);
            FileInfo resourceToBeRemoved = new FileInfo(workDirCssFile);

            FileUtil.DeleteFile(resourceToBeRemoved);
            NUnit.Framework.Assert.IsFalse(resourceToBeRemoved.Exists);
        }
Example #6
0
 private bool LocalDeleteFile(string filePath)
 {
     try
     {
         if (!File.Exists(filePath))
         {
             Log.Error("该文件不存在---FilePath:" + filePath);
             _errmsg = FileNotExist + filePath;
             return(false);
         }
         FileUtil.DeleteFile(filePath);
         //File.Delete(filePath);
         return(true);
     }
     catch (IOException e)
     {
         Log.Error(e);
         _errmsg = e.Message;
         throw new ApplicationException(e.Message);
     }
     catch (Exception e)
     {
         Log.Error(e);
         _errmsg = e.Message;
         throw new ApplicationException(e.Message);
     }
 }
Example #7
0
        internal void ShowRunQueryUrl()
        {
            if (Query == null || Query.UserObject == null || Query.UserObject.Id <= 0)
            {
                MessageBoxMx.ShowError("The query must first be saved.");
                return;
            }

            string folder   = ServicesIniFile.Read("QueryLinksNetworkFolder"); // get unc form of folder
            string fileName = "Run_Query_" + Query.UserObject.Id + ".bat";     // file name
            string uncPath  = folder + '\\' + fileName;                        // unc file to write now and read later

            string       tempFile = TempFile.GetTempFileName();
            StreamWriter sw       = new StreamWriter(tempFile);
            string       cmd      =                                                            // batch command to start the Mobius client and run the specified query
                                    Lex.AddDoubleQuotes(ClientDirs.ExecutablePath) +           // path to executable in quotes
                                    " Mobius:Command='Run Query " + Query.UserObject.Id + "'"; // the mobius command to run

            sw.WriteLine(cmd);
            sw.Close();

            ServerFile.CopyToServer(tempFile, uncPath);
            FileUtil.DeleteFile(tempFile);

            string url = "file:///" + folder.Replace('\\', '/') + "/" + fileName;             // put in "file:" schema & switch slashes to get URL from UNC name

            InputBoxMx.Show(
                "The following URL can be used from a web page " +
                "to start Mobius and run the current query:",
                "Run Query URL",
                url);
            //"Mobius:Command='Run Query " + Query.UserObject.Id + "'"); // this is better but isn't accepted by SharePoint

            return;
        }
Example #8
0
 /// <summary>
 /// 下载线程
 /// </summary>
 private void downHandler()
 {
     try
     {
         logger.Info("downHandler - start");
         this.configService.StopApp();
         ConfigHelp.VersionVO = this.configService.GetNewVersion();
         if (ConfigHelp.VersionVO == null || !ConfigHelp.VersionVO.success || ConfigHelp.VersionVO.versionCode <= ConfigHelp.VersionCode)
         {
             logger.Info("downHandler - version=" + ConfigHelp.VersionVO);
             this.setMessage("当前没有可更新的版本!");
             this.updateLocal();
             return;
         }
         ConfigHelp.FileDownPath   = ConfigHelp.CurrentDirectory + "\\" + ConfigHelp.VersionVO.fileName;
         ConfigHelp.FileUpdatePath = ConfigHelp.CurrentDirectory + "\\" + ConfigHelp.FileUpdataDir;
         this.setVersion("准备升级版本:" + ConfigHelp.VersionVO.versionName);
         FileUtil.DeleteFile(ConfigHelp.FileDownPath);
         FileUtil.DeleteFile(ConfigHelp.FileUpdatePath);
         logger.Info("downHandler - versionName=" + ConfigHelp.VersionVO.versionName + ", versionCode=" + ConfigHelp.VersionVO.versionCode + ", fileName=" + ConfigHelp.VersionVO.fileName + ", fileMd5=" + ConfigHelp.VersionVO.fileMd5 + ", downUrl=" + ConfigHelp.VersionVO.downUrl + ", FileDownPath=" + ConfigHelp.FileDownPath);
         FileDownUtil.DownFileRequest(ConfigHelp.VersionVO.downUrl, ConfigHelp.FileDownPath, this.downDelegate);
         logger.Info("downHandler - over");
         this.isDeleteFile = true;
         this.startCheckThread();
     }
     catch (Exception e)
     {
         this.setMessage("升级包下载失败!");
         this.updateLocal();
         logger.Info("downHandler - e=" + e);
         return;
     }
 }
Example #9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string filepath = Request.Params["filedirectory"];
                filepath = (string.IsNullOrEmpty(filepath)) ? "Accessories/" : filepath + "/";

                string path = Server.MapPath(filepath);
                FileUtil.CreateDirectory(path);
                ////if (Directory.Exists(path) == false)
                ////{
                ////    Directory.CreateDirectory(path);
                ////}
                foreach (string f in Request.Files.AllKeys)
                {
                    HttpPostedFile file   = Request.Files[f];
                    long           offset = long.Parse(Request.Params["offset"]);
                    long           length = long.Parse(Request.Params["length"]);
//					byte [] temp = Encoding.GetEncoding("gb2312").GetBytes(file.FileName);
                    if (offset == length)
                    {
                        file.SaveAs(path + file.FileName);
                        int len = file.ContentLength;
                        Response.Write("OK " + len + " " + len + "\r\n");
                    }
                    else
                    {
                        string tempName = path + file.FileName + offset;
                        file.SaveAs(tempName);
                        byte[] content = null;
                        using (var tempfs = new FileStream(tempName, FileMode.Open, FileAccess.ReadWrite))
                        {
                            content = new byte[tempfs.Length];
                            tempfs.Read(content, 0, content.Length);
                            tempfs.Close();
                        }

                        file.SaveAs(tempName);
                        using (var fs = new FileStream(path + file.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                        {
                            fs.SetLength(length);
                            fs.Position = offset;
                            fs.Write(content, 0, content.Length);
                            fs.Close();
                        }
                        FileUtil.DeleteFile(tempName);
                        //File.Delete(tempName);
                        Response.Write("OK " + offset + " " + (offset + content.Length).ToString() + "\r\n");
                    }
                }
                if (Request.Params["testKey"] != null)
                {
                    Response.Write(Request.Params["testKey"]);
                }
            }
            catch (Exception ex)
            {
                Log.Warn(ex);
            }
        }
Example #10
0
        /// <summary>
        ///     生成模板
        /// </summary>
        /// <returns></returns>
        public async Task <ExportFileInfo> GenerateTemplateFileAsync <T>(string filePath) where T : class, new()
        {
            FileUtil.DeleteFile(filePath);
            var result = await ExcelImporter.GenerateTemplate <T>(filePath);

            return(result);
        }
Example #11
0
 /// <summary>
 /// 成功完成后
 /// </summary>
 private void updateComplate()
 {
     try
     {
         logger.Info("updateComplate - start - isDeleteFile=" + this.isDeleteFile);
         if (this.isDeleteFile)
         {
             logger.Info("updateComplate - delete down path - " + FileUtil.DeleteFile(ConfigHelp.FileDownPath) + ", " + ConfigHelp.FileDownPath);
             logger.Info("updateComplate - delete update path - " + FileUtil.DeleteFile(ConfigHelp.FileUpdatePath) + ", " + ConfigHelp.FileUpdatePath);
         }
         this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
         {
             this.button_confirm.Content = "启动程序";
             if (this.buttonEventHandler != null)
             {
                 this.button_confirm.RemoveHandler(Button.ClickEvent, this.buttonEventHandler);
             }
             this.buttonEventHandler = new RoutedEventHandler(this.button_startApp_ClickHandler);
             this.button_confirm.AddHandler(Button.ClickEvent, this.buttonEventHandler);
             if (ConfigHelp.VersionVO != null)
             {
                 this.configService.SetVersionCodeName(ConfigHelp.VersionVO.versionCode.ToString(), ConfigHelp.VersionVO.versionName);
             }
             logger.Info("updateComplate - end");
         }));
     }
     catch (Exception ex)
     {
         logger.Info("updateComplate - ex=" + ex.ToString());
     }
 }
Example #12
0
        public virtual void TestThatAddedFontIsReleasedAfterConversion()
        {
            // TODO unignore after DEVSIX-3199 is fixed
            String dirName        = "AddedFontIsReleased/";
            String htmlFileName   = "addedFontIsReleased.html";
            String fontFileName   = "NotoSans-Regular.ttf";
            String sourceHtmlFile = sourceFolder + dirName + htmlFileName;
            String sourceFontFile = sourceFolder + dirName + fontFileName;
            String workDir        = destinationFolder + dirName;

            CreateDestinationFolder(workDir);
            String targetPdfFile   = workDir + "target.pdf";
            String workDirFontFile = workDir + fontFileName;

            File.Copy(Path.Combine(sourceFontFile), Path.Combine(workDirFontFile));
            DefaultFontProvider fontProvider = new DefaultFontProvider(true, false, false);

            fontProvider.AddDirectory(workDir);
            ConverterProperties properties = new ConverterProperties().SetBaseUri(sourceFolder).SetFontProvider(fontProvider
                                                                                                                );

            HtmlConverter.ConvertToPdf(new FileInfo(sourceHtmlFile), new FileInfo(targetPdfFile), properties);
            FileInfo resourceToBeRemoved = new FileInfo(workDirFontFile);

            FileUtil.DeleteFile(resourceToBeRemoved);
            NUnit.Framework.Assert.IsFalse(resourceToBeRemoved.Exists);
        }
        public void StartBuildArchive()
        {
            //retrive archivatorDTO object
            archivatorDTO = form1.archivatorDTO;

            if (archivatorDTO != null && archivatorDTO.Delimiter != null && archivatorDTO.Destination != null && archivatorDTO.Source != null && archivatorDTO.StartIndex != null)
            {
                //check if source dir exist on disk
                if (!Directory.Exists(archivatorDTO.Source))
                {
                    ComponentsUtil.AppendTextToRichTextBox(form1.GetRichTextBoxInfo(), "\tSource dir not exist..", Color.Red, true);
                    return;
                }

                //process .meta file and build zipFile
                ComponentsUtil.AppendTextToRichTextBox(form1.GetRichTextBoxInfo(), "\tStarting build archive files..", Color.Green, true);
                ArchiveController archiveCtrl = new ArchiveController(form1);
                bool builtZip = archiveCtrl.BuildZipFile();
                ComponentsUtil.AppendTextToRichTextBox(form1.GetRichTextBoxInfo(), "\tFinished build archive file..", Color.Green, true);

                //if ZipFile was built succesfully then delete .meta from (source ) .meta file unzipped
                if (builtZip)
                {
                    FileUtil.DeleteFile(archiveCtrl.pathMetadata);
                }
            }
        }
Example #14
0
        /// <summary>
        /// 注销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUnreg_Click(object sender, EventArgs e)
        {
            RegistryKey reg;
            string      regkey = UIConstants.SoftwareRegistryKey;

            reg = Registry.CurrentUser.OpenSubKey(regkey, true);
            if (null == reg)
            {
                reg = Registry.CurrentUser.CreateSubKey(regkey);
            }
            if (null != reg)
            {
                reg.SetValue("productName", UIConstants.SoftwareProductName);
                reg.SetValue("version", UIConstants.SoftwareVersion);
                reg.SetValue("SysDate", Data.getSysDate());
                reg.SetValue("regCode", string.Empty);
            }
            AppConfig config = Cache.Instance["AppConfig"] as AppConfig;

            if (config == null)
            {
                config = new AppConfig();
                Cache.Instance["AppConfig"] = config;
            }
            string LicensePath = config.AppConfigGet("LicensePath");

            FileUtil.DeleteFile(LicensePath);
            MessageDxUtil.ShowTips("祝贺您,注销成功");
            Close();
            Application.Exit();
        }
Example #15
0
 /// <summary>
 /// 批量删除文件
 /// </summary>
 /// <param name="fileName"></param>
 public void Delete(IList <string> fileName)
 {
     fileName.ToList().ForEach(item =>
     {
         var filePath = sys_file.GetFilePath(item);
         FileUtil.DeleteFile(filePath);
     });
 }
Example #16
0
/// <summary>
/// DeleteTempFiles
/// </summary>
        static void DeleteTempFiles()
        {
            for (int fi = 0; fi < FingerprintDao.FingerprintFileCount; fi++)
            {
                string fileName = FpDao.GetFpFileName(fi);
                FileUtil.DeleteFile(fileName + ".mrg");
            }
        }
Example #17
0
        /// <summary>
        ///     导出数据
        /// </summary>
        /// <param name="source">数据源</param>
        /// <param name="filePath">保存路径</param>
        /// <param name="templatePath">模板路径</param>
        /// <returns></returns>
        public async Task <ExportFileInfo> ExportFileAsync <T>(T source, string templatePath, string filePath)
            where T : class
        {
            FileUtil.DeleteFile(filePath);
            var result = await ExcelExporter.ExportByTemplate(filePath, source, templatePath);

            return(result);
        }
Example #18
0
 public void DeleteResource()
 {
     Resource.Split(',').Each(t =>
     {
         var name = Path.GetFileName(t.ToString());
         FileUtil.DeleteFile(Constant.Server.MapPath($"~/{SiteName}/resource/{name}"));
     });
 }
Example #19
0
        /// <summary>
        /// 根据文件Key删除文件
        /// </summary>
        /// <param name="fileKey"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public void DeleteFile(string fileKey, params object[] param)
        {
            var fileInfo = this._currentKey.GetFileSavePath(fileKey, param);

            var filepath = this.GetFilePath(fileInfo);

            FileUtil.DeleteFile(filepath);
        }
Example #20
0
 /// <summary>
 ///     导出数据
 /// </summary>
 /// <param name="source">数据源</param>
 /// <param name="filePath">保存路径</param>
 /// <param name="excelHeaders">自定义 Excel 表头</param>
 /// <returns></returns>
 public async Task <ExportFileInfo> ExportFileAsync <T>(List <T> source, string filePath,
                                                        List <ExcelHeader> excelHeaders = null) where T : class
 {
     FileUtil.DeleteFile(filePath);
     return(excelHeaders == null || !excelHeaders.Any()
         ? await ExcelExporter.Export(filePath, source)
         : await ExcelExporter.Export(filePath, ExcelUtil.ToDataTable(source),
                                      new ExcelHeaderFilter(excelHeaders)));
 }
Example #21
0
        public void DeleteTemp()
        {
            var path = GetDeletePath();

            if (path.IsNotNullOrEmpty())
            {
                FileUtil.DeleteFile(GetDeletePath());
            }
        }
 /// <summary>
 /// 基础-删除文件
 /// </summary>
 /// <param name="fileName"></param>
 public void BaseDeleteFile(string fileName)
 {
     if (CheckUtil.StringIsNull(fileName))
     {
         LogUtil.Log("删除文件失败-没有文件路径");
         return;
     }
     FileUtil.DeleteFile(dataStoragePath + "/" + fileName);
 }
        private void btnGetMachineCode_Click(object sender, EventArgs e)
        {
            // 不自动更新排除的文件 license.lic 序列号
            // log              日志文件
            // AutoUpdater      自动更新
            string startupPath = Application.StartupPath;

            if (FileUtil.IsExistFile(startupPath + "\\" + txtFileName.Text.Trim()))
            {
                FileUtil.DeleteFile(startupPath + "\\" + txtFileName.Text.Trim());
            }

            // 写入前面的模板
            FileUtil.AppendText(txtFileName.Text.Trim(), "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n", Encoding.UTF8);
            FileUtil.AppendText(txtFileName.Text.Trim(), "<manifest>\r\n", Encoding.UTF8);
            FileUtil.AppendText(txtFileName.Text.Trim(), "\t<version>" + txtVersion.Text.Trim() + "</version>\r\n", Encoding.UTF8);
            FileUtil.AppendText(txtFileName.Text.Trim(), "\t<description>" + txtUpdateInfo.Text.Trim() + "</description>\r\n", Encoding.UTF8);
            FileUtil.AppendText(txtFileName.Text.Trim(), "\t<!--applicationId运用程序ID,需要与客户端配置一样,否则不会进行更新-->\r\n", Encoding.UTF8);
            FileUtil.AppendText(txtFileName.Text.Trim(), "\t<myapplication applicationId=\"" + txtApplicationId.Text.Trim() + "\">\r\n", Encoding.UTF8);
            FileUtil.AppendText(txtFileName.Text.Trim(), "\t\t<!--暂时没有使用,重新启动exe名称,parameters启动时传入的参数-->\r\n", Encoding.UTF8);
            FileUtil.AppendText(txtFileName.Text.Trim(), "\t\t<entryPoint file=\"" + txtMain.Text.Trim() + "\" parameters=\"" + txtparam.Text.Trim() + "\" />\r\n", Encoding.UTF8);
            FileUtil.AppendText(txtFileName.Text.Trim(), "\t</myapplication>\r\n", Encoding.UTF8);
            FileUtil.AppendText(txtFileName.Text.Trim(), "\t<!--base表示存放该文件的url-->\r\n", Encoding.UTF8);
            FileUtil.AppendText(txtFileName.Text.Trim(), "\t<files base=\"http://www.jcodes.cn/update/Pack/\">\r\n", Encoding.UTF8);
            FileUtil.AppendText(txtFileName.Text.Trim(), "\t\t<!--文件名称-->\r\n", Encoding.UTF8);

            string[] files = DirectoryUtil.GetAllFileNames(startupPath);
            for (Int32 i = 0; i < files.Length; i++)
            {
                // 日志路径
                if (files[i].Contains("log\\"))
                {
                    continue;
                }
                if (files[i].Contains("license.lic"))
                {
                    continue;
                }
                if (files[i].Contains("AutoUpdater"))
                {
                    continue;
                }

                FileStream fsread  = new FileStream(files[i], FileMode.Open, FileAccess.Read, FileShare.Read);
                byte[]     md5File = new byte[fsread.Length];
                fsread.Read(md5File, 0, (int)fsread.Length);                               // 将文件流读取到Buffer中
                fsread.Close();
                string result = MD5Util.MD5Buffer(md5File, 0, md5File.Length);             // 对Buffer中的字节内容算MD5
                string tmp    = files[i].Replace(startupPath + "\\", "");
                FileUtil.AppendText(txtFileName.Text.Trim(), "\t\t<file source=\"" + tmp + "\" md5=\"" + result + "\" checkmd5=\"true\" />\r\n", Encoding.UTF8);
            }
            FileUtil.AppendText(txtFileName.Text.Trim(), "\t</files>\r\n", Encoding.UTF8);
            FileUtil.AppendText(txtFileName.Text.Trim(), "</manifest>\r\n", Encoding.UTF8);

            MessageDxUtil.ShowTips("操作完成");
        }
Example #24
0
        public bool GetKeyExist(CacheKeyInfo keyInfo)
        {
            lock (this)
            {
                string realKey = string.Empty;
                if (keyInfo.CacheKey.IsNativeFile)
                {
                    realKey = keyInfo.GetRealKey();
                }
                else
                {
                    realKey = keyInfo.GetRealKey() + ".cache";
                }

                bool saveDisk = keyInfo.CacheKey.SaveDiskPath != null;
                if (saveDisk)
                {
                    CacheIndex cacheIndex = cacheIndexManager.GetCacheIndex(realKey);
                    if (cacheIndex == null)
                    {
                        return(false);
                    }

                    string filePath = baseCacheDir + cacheIndex.CacheFilePath;
                    if (cacheIndex.ExpireTime > 0)
                    {
                        int now = (int)(TimeManager.Instance.Now / 1000);
                        //过期
                        if (now - cacheIndex.WriteTime >= cacheIndex.ExpireTime)
                        {
                            FileUtil.DeleteFile(filePath);
                            cacheIndexManager.RemoveCacheIndex(realKey);
                            return(false);
                        }
                    }

                    if (fileCache.ContainsKey(realKey))
                    {
                        return(true);
                    }

                    if (!File.Exists(filePath))
                    {
                        FileUtil.DeleteFile(filePath);
                        cacheIndexManager.RemoveCacheIndex(realKey);
                        return(false);
                    }
                    return(true);
                }
                else
                {
                    return(localCache.ContainsKey(realKey));
                }
            }
        }
Example #25
0
        public IActionResult Delete(string type, string name)
        {
            var ret          = new ApiResult <string>();
            var relativePath = $"{type}/{name}.{type}";

            _log.Info($"begin to delete file: {relativePath}");
            FileUtil.DeleteFile(relativePath);
            ret.Code = ApiResultStatus.Success;
            ret.Data = $"delete file: {relativePath} successful";
            return(Json(ret));
        }
Example #26
0
        public void DeleteUploadFileByID(int objectTypeId, int ID)
        {
            UploadFileInfo existingInfo = this.fileDao.GetFileByID(objectTypeId, ID);

            if (existingInfo == null)
            {
                return;
            }

            this.fileDao.DeleteFileByID(objectTypeId, existingInfo.ID);
            FileUtil.DeleteFile(ObjectTypes.GetFileFolder(objectTypeId), existingInfo.GetFileName());
        }
Example #27
0
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            string path = txtPath.Text.Trim();

            if (string.IsNullOrEmpty(path))
            {
                path = FileDialogHelper.OpenDir();
            }

            string fileRecord    = "F:\\oldfile.txt";
            string fileNewReocrd = "F:\\newfile.txt";

            if (FileUtil.IsExistFile(fileRecord))
            {
                FileUtil.DeleteFile(fileRecord);
            }
            FileUtil.CreateFile(fileRecord);

            if (FileUtil.IsExistFile(fileNewReocrd))
            {
                FileUtil.DeleteFile(fileNewReocrd);
            }
            FileUtil.CreateFile(fileNewReocrd);

            Int32 copyCount = 0;

            if (!string.IsNullOrEmpty(path))
            {
                string[] files = DirectoryUtil.GetFileNames(path, "*", true);

                foreach (var file in files)
                {
                    FileUtil.AppendText(fileRecord, file + "\r\n", Encoding.UTF8);

                    string oldfilerelatefile = file.Replace(path + "\\", "");
                    string newfllerelatefile = oldfilerelatefile.Replace("\\", "_");
                    if (FileUtil.IsExistFile(file) && oldfilerelatefile != newfllerelatefile)
                    {
                        File.Move(file, path + "\\" + newfllerelatefile);
                        copyCount++;
                    }
                }

                files = DirectoryUtil.GetFileNames(path, "*", true);
                foreach (var file in files)
                {
                    FileUtil.AppendText(fileNewReocrd, file + "\r\n", Encoding.UTF8);
                }
            }

            MessageDxUtil.ShowTips("操作完成, 一共成功复制" + copyCount + "个文件");
        }
Example #28
0
        public byte[] SaveBytes(ImageFormat format)
        {
            // TODO: for Windows you can save a stream. Need to look into Cairo, but this may be the only way for OSX.
            string seed = IdGenerator.GetRandomSeed();
            string file = FileUtil.JoinPath(
                FileUtil.GetTempDirectory(),
                "crayon-" + IdGenerator.Generate32HexDigits(seed, "image") + FormatToExtension(format));

            this.Save(file);
            byte[] bytes = FileUtil.ReadFileBytes(file);
            FileUtil.DeleteFile(file);
            return(bytes);
        }
Example #29
0
        static void Main(string[] args)
        {
            // Datei löschen
            if (FileUtil.DeleteFile(@"c:\autoexec.bat.copy"))
            {
                Console.WriteLine("Datei erfolgreich gelöscht");
            }
            else
            {
                Console.WriteLine("Datei nicht erfolgreich gelöscht");
            }

            Console.ReadLine();
        }
Example #30
0
 /// <summary>
 /// 异步批量插入(目前只支持MSSQLServer)
 /// </summary>
 /// <param name="table">table</param>
 /// <param name="tableName">表名字</param>
 /// <returns>Task</returns>
 public Task BulkInsertAsync(DataTable table, string tableName)
 {
     return(SqlMonitorUtil.MonitorAsync(async() =>
     {
         if (table != null && DatabaseTyoe == DatabaseType.MSSQLServer)
         {
             Open();
             using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(Connection as SqlConnection, SqlBulkCopyOptions.Default, Tran as SqlTransaction))
             {
                 sqlbulkcopy.BatchSize = table.Rows.Count;
                 sqlbulkcopy.DestinationTableName = tableName;
                 for (int i = 0; i < table.Columns.Count; i++)
                 {
                     sqlbulkcopy.ColumnMappings.Add(table.Columns[i].ColumnName, table.Columns[i].ColumnName);
                 }
                 await sqlbulkcopy.WriteToServerAsync(table.CreateDataReader());
             }
         }
         else if (table != null && DatabaseTyoe == DatabaseType.MySql)
         {
             string tmpPath = System.IO.Path.GetTempFileName();
             try
             {
                 string csv = table.ToCsv();
                 System.IO.File.WriteAllText(tmpPath, csv);
                 Open();
                 MySqlBulkLoader bulk = new MySqlBulkLoader(Connection as MySqlConnection)
                 {
                     FieldTerminator = ",",
                     FieldQuotationCharacter = '"',
                     EscapeCharacter = '"',
                     LineTerminator = "\r\n",
                     FileName = tmpPath,
                     NumberOfLinesToSkip = 0,
                     TableName = tableName,
                 };
                 bulk.Columns.AddRange(table.Columns.Cast <DataColumn>().Select(colum => colum.ColumnName).ToList());
                 int insertCount = await bulk.LoadAsync();
             }
             finally
             {
                 FileUtil.DeleteFile(tmpPath);
             }
         }
         else
         {
             throw new NotSupportedException(DatabaseTyoe.ToString());
         }
     }, dbType: DatabaseTyoe.ToString(), memberName: "BaseDataAccess-BulkInsert"));
 }