System.IO.FileInfo.Delete()

Here are the examples of the csharp api System.IO.FileInfo.Delete() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

742 Examples 7

19 View Source File : FileLoggerProvider.cs
License : MIT License
Project Creator : andrewlock

protected void RollFiles()
        {
            if (_maxRetainedFiles > 0)
            {
                var groupsToDelete = new DirectoryInfo(_path)
                    .GetFiles(_fileName + "*")
                    .GroupBy(file => GetFilenameForGrouping(file.Name))
                    .OrderByDescending(f => f.Key)
                    .Skip(_maxRetainedFiles.Value);

                foreach (var groupToDelete in groupsToDelete)
                {
                    foreach (var fileToDelete in groupToDelete)
                    {
                        fileToDelete.Delete();
                    }
                }
            }

            string GetFilenameForGrouping(string filename)
            {
                var hasExtension = !string.IsNullOrEmpty(_extension);
                var isMultiFile = _maxFileCountPerPeriodicity > 1;
                return (isMultiFile, hasExtension) switch
                {
                    (false, false) => filename,
                    (false, true) => Path.GetFileNameWithoutExtension(filename),
                    (true, false) => Path.GetFileNameWithoutExtension(filename),
                    (true, true) => Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(filename)),
                };
            }

19 View Source File : Issues.cs
License : Apache License 2.0
Project Creator : Appdynamics

[TestMethod]
        public void Issue15056()
        {
            var path = @"C:\temp\output.xlsx";
            var file = new FileInfo(path);
            file.Delete();
            using (var ep = new ExcelPackage(file))
            {
                var s = ep.Workbook.Worksheets.Add("test");
                s.Cells["A1:A2"].Formula = ""; // or null, or non-empty whitespace, with same result
                ep.Save();
            }

        }

19 View Source File : ExperimentFileController.cs
License : MIT License
Project Creator : AlexanderFroemmgen

[HttpPost("{name}/configs/{configName}/delete")]
        public IActionResult DeleteConfig(string name, string configName)
        {
            var filename = relativeFolder + "/" + name + "/configurations/" + configName + ".json";
            if (isValidPath(filename))
            {
                new FileInfo(filename).Delete();
                GitIntegration.CreateBackup(relativeFolder + "/" + name, "delete config " + configName, _gitRemoteOptions);
                return Ok();
            }
            else
            {
                return BadRequest("Invalid name.");
            }
        }

19 View Source File : Netch.cs
License : MIT License
Project Creator : AmazingDM

[STAThread]
        public static void Main(string[] args)
        {
            if (args.Contains("-console"))
            {
                if (!NativeMethods.AttachConsole(-1))
                {
                    NativeMethods.AllocConsole();
                }
            }

            // 创建互斥体防止多次运行
            using (var mutex = new Mutex(false, "Global\\Netch"))
            {
                // 设置当前目录
                Directory.SetCurrentDirectory(Global.NetchDir);
                Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Process) + ";" + Path.Combine(Global.NetchDir, "bin"), EnvironmentVariableTarget.Process);

                // 预创建目录
                var directories = new[] {"mode", "data", "i18n", "logging"};
                foreach (var item in directories)
                {
                    if (!Directory.Exists(item))
                    {
                        Directory.CreateDirectory(item);
                    }
                }

                // 加载配置
                Configuration.Load();

                // 加载语言
                i18N.Load(Global.Settings.Language);

                // 检查是否已经运行
                /*if (!mutex.WaitOne(0, false))
                {
                    OnlyInstance.Send(OnlyInstance.Commands.Show);
                    Logging.Info("唤起单实例");

                    // 退出进程
                    Environment.Exit(1);
                }*/

                // 清理上一次的日志文件,防止淤积占用磁盘空间
                if (Directory.Exists("logging"))
                {
                    var directory = new DirectoryInfo("logging");

                    foreach (var file in directory.GetFiles())
                    {
                        file.Delete();
                    }

                    foreach (var dir in directory.GetDirectories())
                    {
                        dir.Delete(true);
                    }
                }

                Logging.Info($"版本: {UpdateChecker.Owner}/{UpdateChecker.Repo}@{UpdateChecker.Version}");
                Task.Run(() =>
                {
                    Logging.Info($"主程序 SHA256: {Utils.Utils.SHA256CheckSum(Application.ExecutablePath)}");
                });
                Task.Run(() =>
                {
                    Logging.Info("启动单实例");
                    OnlyInstance.Server();
                });

                // 绑定错误捕获
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                Application.ThreadException += Application_OnException;

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(Global.MainForm = new MainForm());
            }
        }

19 View Source File : EditorSettings.cs
License : Apache License 2.0
Project Creator : Algoryx

private static void OnBuildPackage()
    {
      var dataFilesToExclude = new string[]
      {
        EditorDataDirectory + "/Data.replacedet",
        EditorDataDirectory + "/Settings.replacedet"
      };

      if ( Manager.ConfigureEnvironment() != Manager.EnvironmentState.Initialized ) {
        Debug.LogError( "Unable to initialize AGX Dynamics - missing dll(s)?" );
        EditorApplication.Exit( 1 );
        return;
      }

      Debug.Log( "Applying package build settings..." );
      foreach ( var excludedFile in dataFilesToExclude ) {
        var fi = new FileInfo( excludedFile );
        var fiMeta = new FileInfo( excludedFile + ".meta" );
        Debug.Log( $"    - Deleting {fi.FullName}, exist = {fi.Exists}." );
        if ( fi.Exists ) {
          fi.Delete();
          if ( fiMeta.Exists )
            fiMeta.Delete();
        }
      }

      Debug.Log( "    - Adding define symbol AGXUNITY_BUILD_PACKAGE." );
      Build.DefineSymbols.Add( "AGXUNITY_BUILD_PACKAGE" );
    }

19 View Source File : PdbFile.cs
License : MIT License
Project Creator : Akaion

private static async Task<string> DownloadPdb(DebugData debugData, bool isWow64)
        {
            // Ensure a directory exists on disk for the PDB

            var directoryInfo = Directory.CreateDirectory(isWow64 ? Path.Combine(Path.GetTempPath(), "Bleak", "PDB", "WOW64") : Path.Combine(Path.GetTempPath(), "Bleak", "PDB", "x64"));

            var pdbName = $"{debugData.Name}-{debugData.Guid}-{debugData.Age}.pdb";

            var pdbPath = Path.Combine(directoryInfo.FullName, pdbName);

            // Determine if the PDB has already been downloaded

            if (directoryInfo.EnumerateFiles().Any(file => file.Name == pdbName))
            {
                return pdbPath;
            }

            // Clear the directory

            foreach (var file in directoryInfo.EnumerateFiles())
            {
                try
                {
                    file.Delete();
                }

                catch (Exception)
                {
                    // The file is currently open and cannot be safely deleted
                }
            }

            // Download the PDB

            var pdbUri = new Uri($"http://msdl.microsoft.com/download/symbols/{debugData.Name}/{debugData.Guid}{debugData.Age}/{debugData.Name}");

            void ReportDownloadProgress(object sender, ProgressChangedEventArgs eventArgs)
            {
                var progress = eventArgs.ProgressPercentage / 2;

                Console.Write($"\rDownloading required files - [{new string('=', progress)}{new string(' ', 50 - progress)}] - {eventArgs.ProgressPercentage}%");
            }

            using var webClient = new WebClient();

            webClient.DownloadProgressChanged += ReportDownloadProgress;

            await webClient.DownloadFileTaskAsync(pdbUri, pdbPath);

            return pdbPath;
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : ap0405140

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            string tmpstr;
            DirectoryInfo di;

            try
            {
                tmpstr = txtConnectionstring.Text;
                config.AppSettings.Settings.Remove("DefaultConnectionString");
                config.AppSettings.Settings.Add("DefaultConnectionString", tmpstr);
                config.Save(ConfigurationSaveMode.Minimal);

                tmpstr = Application.StartupPath + "\\temp\\";
                di = new DirectoryInfo(tmpstr);
                if (di.Exists == true)
                {
                    foreach (FileInfo tf in di.GetFiles())
                    {
                        tf.Delete();
                    }
                }
            }
            catch(Exception ex)
            {

            }
        }

19 View Source File : EncryptedDirectory.cs
License : MIT License
Project Creator : Adoxio

public override void DeleteFile(string name)
		{
			var file = this.GetRecord(name);
			try
			{
				file.Delete();
			}
			catch (Exception)
			{
				throw new IOException("Cannot delete " + file);
			}
		}

19 View Source File : Issues.cs
License : Apache License 2.0
Project Creator : Appdynamics

[TestMethod]
        public void Issue15460WithNull()
        {
            FileInfo file = new FileInfo("report.xlsx");
            try
            {
                if (file.Exists)
                    file.Delete();
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    var sheet = package.Workbook.Worksheets.Add("New Sheet");
                    sheet.Cells[3, 3].Value = new[] { null, "value2", "value3" };
                    package.Save();
                }
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    var sheet = package.Workbook.Worksheets["New Sheet"];
                    replacedert.AreEqual(string.Empty, sheet.Cells[3, 3].Value);
                }
            }
            finally
            {
                if (file.Exists)
                    file.Delete();
            }
        }

19 View Source File : deviceidmanager.cs
License : MIT License
Project Creator : Adoxio

public static void WriteDevice(ClientCredentials deviceCredentials)
		{
			var deviceId = deviceCredentials.UserName.UserName;

			var deviceName = deviceId.StartsWith(DevicePrefix) & deviceId.Length > MaxDeviceNameLength ? deviceId.Substring(DevicePrefix.Length) : deviceId;

			var userName = new DeviceUserName() { DeviceName = deviceName, DecryptedPreplacedword = deviceCredentials.UserName.Preplacedword };

			var device = new LiveDevice() { User = userName, Version = 1 };

			var file = GetDeviceFile(null);

			if (file.Exists)
			{
				file.Delete();
			}

			WriteDevice(null, device);
		}

19 View Source File : FileSystemResultsWriter.cs
License : Apache License 2.0
Project Creator : allure-framework

public void CleanUp()
    {
      using (var mutex = new Mutex(false, "729dc988-0e9c-49d0-9e50-17e0df3cd82b"))
      {
        mutex.WaitOne();
        var directory = new DirectoryInfo(outputDirectory);
        foreach (var file in directory.GetFiles()) file.Delete();
        foreach (var dir in directory.GetDirectories()) dir.Delete(true);

        mutex.ReleaseMutex();
      }
    }

19 View Source File : PathExtensions.cs
License : MIT License
Project Creator : aliakseiherman

public static void Empty(this DirectoryInfo directory)
        {
            foreach (FileInfo file in directory.GetFiles()) file.Delete();
            foreach (DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
        }

19 View Source File : ReadWrite.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

public static void DeleteSave()
        {
            System.IO.DirectoryInfo di = new DirectoryInfo([email protected]"saves\");
            foreach (FileInfo file in di.GetFiles())
                file.Delete();
            di = new DirectoryInfo([email protected]"saves\data");
            foreach (FileInfo file in di.GetFiles())
                file.Delete();
        }

19 View Source File : VMFileInfo.cs
License : MIT License
Project Creator : ancientproject

public override void Delete() => raw?.Delete();

19 View Source File : IOUtil.cs
License : MIT License
Project Creator : actions

public static void DeleteFile(string path)
        {
            ArgUtil.NotNullOrEmpty(path, nameof(path));
            var file = new FileInfo(path);
            if (file.Exists)
            {
                RemoveReadOnly(file);
                file.Delete();
            }
        }

19 View Source File : CatalogContextSeed.cs
License : MIT License
Project Creator : anjoy8

private void GetCatalogItemPictures(string contentRootPath, string picturePath)
        {
            if (picturePath != null)
            {
                DirectoryInfo directory = new DirectoryInfo(picturePath);
                foreach (FileInfo file in directory.GetFiles())
                {
                    file.Delete();
                }

                string zipFileCatalogItemPictures = Path.Combine(contentRootPath, "Setup", "CatalogItems.zip");
                ZipFile.ExtractToDirectory(zipFileCatalogItemPictures, picturePath);
            }
        }

19 View Source File : AssetBundleReporter.cs
License : MIT License
Project Creator : akof1314

public static void PrintToExcel(string outputPath)
        {
            EditorUtility.DisplayProgressBar("replacedetBundle报告", "正在写入 Excel 文件...", 0.85f);
            var newFile = new FileInfo(outputPath);
            if (newFile.Exists)
            {
                newFile.Delete();
            }

            using (var package = new ExcelPackage(newFile))
            {
                replacedetBundleFilesReporter.CreateWorksheet(package.Workbook.Worksheets);
                replacedetBundleDetailsReporter.CreateWorksheet(package.Workbook.Worksheets);
                replacedetBundleResReporter.CreateWorksheet(package.Workbook.Worksheets);

                replacedetBundleFilesReporter.FillWorksheet(package.Workbook.Worksheets[1]);
                replacedetBundleDetailsReporter.FillWorksheet(package.Workbook.Worksheets[2]);
                replacedetBundleResReporter.FillWorksheet(package.Workbook.Worksheets[3]);

                replacedetBundlePropertyReporter.CreateAndFillWorksheet(package.Workbook.Worksheets, replacedetFileInfoType.mesh);
                replacedetBundlePropertyReporter.CreateAndFillWorksheet(package.Workbook.Worksheets, replacedetFileInfoType.texture2D);
                replacedetBundlePropertyReporter.CreateAndFillWorksheet(package.Workbook.Worksheets, replacedetFileInfoType.material);
                replacedetBundlePropertyReporter.CreateAndFillWorksheet(package.Workbook.Worksheets, replacedetFileInfoType.animationClip);
                replacedetBundlePropertyReporter.CreateAndFillWorksheet(package.Workbook.Worksheets, replacedetFileInfoType.audioClip);

                package.Save();
            }

            replacedetBundleFilesreplacedyze.Clear();
            EditorUtility.ClearProgressBar();
        }

19 View Source File : CompoundDoc.cs
License : Apache License 2.0
Project Creator : Appdynamics

[TestMethod, Ignore]
        public void Sample7EncrLargeTest()
        {
            int Rows = 1000000;
            int colMult = 20;
            FileInfo newFile = new FileInfo(@"C:\temp\bug\sample7compdoctest.xlsx");
            if (newFile.Exists)
            {
                newFile.Delete();  // ensures we create a new workbook
                newFile = new FileInfo(@"C:\temp\bug\sample7compdoctest.xlsx");
            }
            using (ExcelPackage package = new ExcelPackage())
            {
                Console.WriteLine("{0:HH.mm.ss}\tStarting...", DateTime.Now);

                //Load the sheet with one string column, one date column and a few random numbers.
                var ws = package.Workbook.Worksheets.Add("Performance Test");

                //Format all cells
                ExcelRange cols = ws.Cells["A:XFD"];
                cols.Style.Fill.PatternType = ExcelFillStyle.Solid;
                cols.Style.Fill.BackgroundColor.SetColor(Color.LightGray);

                var rnd = new Random();
                for (int row = 1; row <= Rows; row++)
                {
                    for (int c = 0; c < colMult * 5; c += 5)
                    {
                        ws.SetValue(row, 1 + c, row);                               //The SetValue method is a little bit faster than using the Value property
                        ws.SetValue(row, 2 + c, string.Format("Row {0}", row));
                        ws.SetValue(row, 3 + c, DateTime.Today.AddDays(row));
                        ws.SetValue(row, 4 + c, rnd.NextDouble() * 10000); 
                     }
                }
                var endC = colMult * 5;
                ws.Cells[1, endC, Rows, endC].FormulaR1C1 = "RC[-4]+RC[-1]";

                //Add a sum at the end
                ws.Cells[Rows + 1, endC].Formula = string.Format("Sum({0})", new ExcelAddress(1, 5, Rows, 5).Address);
                ws.Cells[Rows + 1, endC].Style.Font.Bold = true;
                ws.Cells[Rows + 1, endC].Style.Numberformat.Format = "#,##0.00";

                Console.WriteLine("{0:HH.mm.ss}\tWriting row {1}...", DateTime.Now, Rows);
                Console.WriteLine("{0:HH.mm.ss}\tFormatting...", DateTime.Now);
                //Format the date and numeric columns
                ws.Cells[1, 1, Rows, 1].Style.Numberformat.Format = "#,##0";
                ws.Cells[1, 3, Rows, 3].Style.Numberformat.Format = "YYYY-MM-DD";
                ws.Cells[1, 4, Rows, 5].Style.Numberformat.Format = "#,##0.00";

                Console.WriteLine("{0:HH.mm.ss}\tInsert a row at the top...", DateTime.Now);
                //Insert a row at the top. Note that the formula-addresses are shifted down
                ws.InsertRow(1, 1);

                //Write the headers and style them
                ws.Cells["A1"].Value = "Index";
                ws.Cells["B1"].Value = "Text";
                ws.Cells["C1"].Value = "Date";
                ws.Cells["D1"].Value = "Number";
                ws.Cells["E1"].Value = "Formula";
                ws.View.FreezePanes(2, 1);

                using (var rng = ws.Cells["A1:E1"])
                {
                    rng.Style.Font.Bold = true;
                    rng.Style.Font.Color.SetColor(Color.White);
                    rng.Style.WrapText = true;
                    rng.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                    rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                    rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
                    rng.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue);
                }

                //Calculate (Commented away thisk, it was a bit time consuming... /MA)
                // Console.WriteLine("{0:HH.mm.ss}\tCalculate formulas...", DateTime.Now);
                // ws.Calculate();

                Console.WriteLine("{0:HH.mm.ss}\tAutofit columns and lock and format cells...", DateTime.Now);
                ws.Cells[Rows - 100, 1, Rows, 5].AutoFitColumns(5);   //Auto fit using the last 100 rows with minimum width 5
                ws.Column(5).Width = 15;                            //We need to set the width for column F manually since the end sum formula is the widest cell in the column (EPPlus don't calculate any forumlas, so no output text is avalible). 

                //Now we set the sheetprotection and a preplacedword.
                ws.Cells[2, 3, Rows + 1, 4].Style.Locked = false;
                ws.Cells[2, 3, Rows + 1, 4].Style.Fill.PatternType = ExcelFillStyle.Solid;
                ws.Cells[2, 3, Rows + 1, 4].Style.Fill.BackgroundColor.SetColor(Color.White);
                ws.Cells[1, 5, Rows + 2, 5].Style.Hidden = true;    //Hide the formula

                ws.Protection.SetPreplacedword("EPPlus");

                ws.Select("C2");
                Console.WriteLine("{0:HH.mm.ss}\tSaving...", DateTime.Now);
                package.Compression = CompressionLevel.BestSpeed;
                package.Encryption.IsEncrypted = true;
                package.SaveAs(newFile);
            }
            Console.WriteLine("{0:HH.mm.ss}\tDone!!", DateTime.Now);
        }

19 View Source File : AssetBundleUtil.cs
License : MIT License
Project Creator : 404Lcc

public static void BuildreplacedetBundle(replacedetBundleSetting replacedetBundleSetting)
        {
            Dictionary<string, replacedetBundleData> replacedetBundleDataDict = new Dictionary<string, replacedetBundleData>();
            Dictionary<string, replacedetBundleRuleType> replacedetBundleRuleTypeDict = new Dictionary<string, replacedetBundleRuleType>();
            string path = PathUtil.GetPath(PathType.DataPath, replacedetBundleSetting.outputPath, GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget));
            foreach (DirectoryInfo item in DirectoryUtil.GetDirectorys(new DirectoryInfo(path), new List<DirectoryInfo>()))
            {
                item.Delete();
            }
            foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(path), new List<FileInfo>()))
            {
                item.Delete();
            }
            List<replacedetBundleBuild> replacedetBundleBuildList = new List<replacedetBundleBuild>();
            foreach (replacedetBundleRule item in replacedetBundleSetting.replacedetBundleRuleList)
            {
                if (item.replacedetBundleRuleType == replacedetBundleRuleType.File)
                {
                    FileInfo[] fileInfos = FileUtil.GetFiles(new DirectoryInfo(item.path), new List<FileInfo>());
                    if (fileInfos.Length == 0) continue;
                    List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
                    foreach (FileInfo fileInfo in fileInfoList)
                    {
                        replacedetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/"), replacedetBundleRuleType.File);
                    }
                }
                if (item.replacedetBundleRuleType == replacedetBundleRuleType.Directory)
                {
                    DirectoryInfo[] directoryInfos = DirectoryUtil.GetDirectorys(new DirectoryInfo(item.path), new List<DirectoryInfo>());
                    if (directoryInfos.Length == 0) continue;
                    foreach (DirectoryInfo directoryInfo in directoryInfos)
                    {
                        FileInfo[] fileInfos = directoryInfo.GetFiles();
                        if (fileInfos.Length == 0) continue;
                        List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
                        foreach (FileInfo fileInfo in fileInfoList)
                        {
                            replacedetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/"), replacedetBundleRuleType.Directory);
                        }
                    }
                }
            }
            foreach (replacedetBundleData item in replacedetBundleSetting.replacedetBundleDataList)
            {
                replacedetBundleBuildList.Add(new replacedetBundleBuild()
                {
                    replacedetBundleName = item.replacedetBundleName,
                    replacedetNames = item.replacedetNames,
                });
            }
            replacedetBundleManifest replacedetBundleManifest = BuildPipeline.BuildreplacedetBundles(path, replacedetBundleBuildList.ToArray(), BuildreplacedetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
            foreach (replacedetBundleData item in replacedetBundleSetting.replacedetBundleDataList)
            {
                item.replacedetBundleHash = replacedetBundleManifest.GetreplacedetBundleHash(item.replacedetBundleName).ToString();
                BuildPipeline.GetCRCForreplacedetBundle($"{path}/{item.replacedetBundleName}", out item.replacedetBundleCRC);
                item.fileSize = FileUtil.GetFileSize($"{path}/{item.replacedetBundleName}");
                replacedetBundleDataDict.Add(Path.GetFileNameWithoutExtension(item.replacedetBundleName), item);
            }
            replacedetBundleConfig replacedetBundleConfig = new replacedetBundleConfig(replacedetBundleSetting.buildId, replacedetBundleDataDict, replacedetBundleRuleTypeDict);
            FileUtil.Savereplacedet(path, "replacedetBundleConfig.json", JsonUtil.ToJson(replacedetBundleConfig));
            if (replacedetBundleSetting.isCopyStreamingreplacedets)
            {
                string copyPath = PathUtil.GetPath(PathType.StreamingreplacedetsPath, "Res", GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget));
                foreach (DirectoryInfo item in DirectoryUtil.GetDirectorys(new DirectoryInfo(copyPath), new List<DirectoryInfo>()))
                {
                    item.Delete();
                }
                foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(copyPath), new List<FileInfo>()))
                {
                    item.Delete();
                }
                foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(path), new List<FileInfo>()))
                {
                    if (Path.GetExtension(item.Name) == ".meta") continue;
                    File.Copy(item.FullName, $"{PathUtil.GetPath(PathType.StreamingreplacedetsPath, "Res", GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget))}/{item.Name}");
                }
            }
            replacedetDatabase.Refresh();
        }

19 View Source File : Issues.cs
License : Apache License 2.0
Project Creator : Appdynamics

[TestMethod]
        public void Issue15460WithString()
        {
            FileInfo file = new FileInfo("report.xlsx");
            try
            {
                if (file.Exists)
                    file.Delete();
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    var sheet = package.Workbook.Worksheets.Add("New Sheet");
                    sheet.Cells[3, 3].Value = new[] { "value1", "value2", "value3" };
                    package.Save();
                }
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    var sheet = package.Workbook.Worksheets["New Sheet"];
                    replacedert.AreEqual("value1", sheet.Cells[3, 3].Value);
                }
            }
            finally
            {
                if (file.Exists)
                    file.Delete();
            }
        }

19 View Source File : CompressAndEncryptBenchmark.cs
License : MIT License
Project Creator : alexis-

public static long Process(
      Stream data,
      ArchiveType archiveType, CompressionType compType,
      EncryptionProtocol encProtocol, EncryptionAlgorithm encAlgorithm)
    {
      string fileName = Path.GetTempFileName();
      FileInfo fileInfo = new FileInfo(fileName);
      long compSizeB = 0;

      ProgressStreamReportDelegate progressCallback =
        (_, args) => compSizeB += args.BytesMoved;

      using (Stream outFileStream = fileInfo.OpenWrite())
      {
        Action<Stream> streamWriter =
          (outStream) => CompressionHelper.Compress(
            "data.bin",
            data,
            outStream,
            archiveType,
            compType,
            progressCallback
          );

        switch (encProtocol)
        {
          case EncryptionProtocol.None:
            streamWriter(outFileStream);
            break;

          case EncryptionProtocol.AES:
            EncryptionHelper.EncryptStreamAES(streamWriter, outFileStream, encAlgorithm, Const.EncKey32);
            break;

          case EncryptionProtocol.PBE:
            EncryptionHelper.EncryptStreamPBE(streamWriter, outFileStream, encAlgorithm, Const.EncKey32);
            break;

          case EncryptionProtocol.PGP:
            using (Stream pgpPubKeyStream = new MemoryStream(Encoding.ASCII.GetBytes(Const.PGPPubKey)))
            EncryptionHelper.EncryptStreamPGP(
              streamWriter, outFileStream, encAlgorithm,
              pgpPubKeyStream, Convert.ToInt64(Const.PGPPubKeyID, 16));
            break;
        }
      }

      fileInfo.Delete();

      return compSizeB;
    }

19 View Source File : CustomEditorGenerator.cs
License : Apache License 2.0
Project Creator : Algoryx

private static void DeleteFile( FileInfo info )
    {
      FileInfo meta = new FileInfo( info.Name + ".meta" );
      info.Delete();
      if ( meta.Exists )
        meta.Delete();
    }

19 View Source File : GameDataManager.cs
License : MIT License
Project Creator : 404Lcc

public void DeleteUserData(string name = "user")
        {
            if (UserDataExist(name))
            {
                FileInfo fileInfo = new FileInfo($"{PathUtil.GetPath(PathType.PersistentDataPath, "Res")}/{name}.lcc");
                fileInfo.Delete();
                userData = null;
            }
        }

19 View Source File : BuildProcessCallbacksHandler.cs
License : Apache License 2.0
Project Creator : Algoryx

private static void PostBuildInternal( string agxDynamicsPath,
                                           string agxPluginPath,
                                           FileInfo targetExecutableFileInfo,
                                           string targetDataPath )
    {
      // Some versions of Unity 2019.3 (fixed in 2019.3.9) isn't consistent
      // where native modules are located. E.g., if Burst is installed, some
      // dll's will be created in <project>_Data/Plugins/x86_64 and if AGX
      // dll's are in <project>_Data/Plugins, the dll's wont load.
      //     - Unity 2019.3 and later:   <project>_Data/Plugins/x86_64
      //     - Unity 2019.2 and earlier: <project>_Data/Plugins
      if ( !Directory.Exists( AGXUnity.IO.Environment.GetPlayerPluginPath( targetDataPath ) ) )
        Directory.CreateDirectory( AGXUnity.IO.Environment.GetPlayerPluginPath( targetDataPath ) );

      // replaceduming all dlls are present in the plugins directory and that
      // "Components" are in a folder named "agx" in the plugins directory.
      // Unity will copy the dlls.
      var sourceDirectory      = new DirectoryInfo( IO.Utils.AGXUnityPluginDirectoryFull + Path.DirectorySeparatorChar + "agx" );
      var destinationDirectory = new DirectoryInfo( AGXUnity.IO.Environment.GetPlayerAGXRuntimePath( targetDataPath ) );
      Debug.Log( GUI.AddColorTag( "Copying AGX runtime data from: " +
                                  IO.Utils.AGXUnityPluginDirectory +
                                  Path.DirectorySeparatorChar +
                                  "agx" +
                                  " to " +
                                  destinationDirectory.FullName, Color.green ) );
      CopyDirectory( sourceDirectory, destinationDirectory );

      // Deleting all .meta-files that are present in our "agx" folder.
      foreach ( var fi in destinationDirectory.EnumerateFiles( "*.meta", SearchOption.AllDirectories ) )
        fi.Delete();

      VerifyBuild( targetDataPath );

      CheckGenerateEncryptedRuntime( targetExecutableFileInfo );
    }

19 View Source File : ServerPreset.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public void Delete()
        {
            FileInfo info = new FileInfo(Path + Name + Extension);
            if (info.Exists)
            {
                info.Delete();
            }
        }

19 View Source File : StanfordNLPClassifier.cs
License : MIT License
Project Creator : allisterb

protected override StageResult Cleanup()
        {
            if (!KeepPropsFile && ClreplacedifierPropsFile != null && ClreplacedifierPropsFile.Exists)
            {
                ClreplacedifierPropsFile.Delete();
            }
            return StageResult.SUCCESS;
        }

19 View Source File : DirectoryContentHandler.cs
License : Apache License 2.0
Project Creator : Algoryx

public void DeleteAllCollected()
    {
      EditorApplication.LockReloadreplacedemblies();

      Debug.Log( "    - Ignoring delete of files:" );
      foreach ( var file in m_ignoredFiles )
        Debug.Log( $"        {file.FullName}" );

      Debug.Log( $"    - Deleting {m_files.Count} files..." );
      foreach ( var file in m_files ) {
        try {
          file.Delete();
        }
        catch ( System.Exception e ) {
          Debug.LogError( $"        Unable to remove file: {file.FullName}\n                {e.Message}" );
        }
      }

      var directories = Directories;
      Debug.Log( $"    - Deleting {directories.Length} directories..." );
      foreach ( var directory in directories ) {
        var directoryPath = directory.FullName.PrettyPath();
        if ( Directory.Exists( directoryPath ) && MayDelete( directory ) ) {
          try {
            Directory.Delete( directoryPath, true );
          }
          catch ( System.Exception e ) {
            Debug.LogError( $"        Unable to remove directory: {directory.FullName}\nIs it open in File Explorer or cmd?\n\n" +
                            $"        {e.Message}" );
          }
        }
      }

      EditorApplication.UnlockReloadreplacedemblies();
    }

19 View Source File : File.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public void Delete()
        {
            lock (locker)
            {
                Dispose();
                info.Delete();
            }
        }

19 View Source File : ModDownloader.cs
License : GNU General Public License v3.0
Project Creator : amakvana

private void DeleteModData(string path)
        {
            DirectoryInfo dir = new DirectoryInfo(path);

            foreach (FileInfo fi in dir.GetFiles())
            {
                fi.Delete();
            }

            foreach (DirectoryInfo di in dir.GetDirectories())
            {
                DeleteModData(di.FullName);
                di.Delete();
            }
        }

19 View Source File : HostTraceListener.cs
License : MIT License
Project Creator : actions

private StreamWriter CreatePageLogWriter()
        {
            if (_enableLogRetention)
            {
                DirectoryInfo diags = new DirectoryInfo(_logFileDirectory);
                var logs = diags.GetFiles($"{_logFilePrefix}*.log");
                foreach (var log in logs)
                {
                    if (log.LastWriteTimeUtc.AddDays(_retentionDays) < DateTime.UtcNow)
                    {
                        try
                        {
                            log.Delete();
                        }
                        catch (Exception)
                        {
                            // catch Exception and continue
                            // we shouldn't block logging and fail the runner if the runner can't delete an older log file.
                        }
                    }
                }
            }

            string fileName = StringUtil.Format(_logFileNamingPattern, _logFilePrefix, DateTime.UtcNow);
            string logFile = Path.Combine(_logFileDirectory, fileName);
            Stream logStream;
            if (File.Exists(logFile))
            {
                logStream = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.Read, bufferSize: 4096);
            }
            else
            {
                logStream = new FileStream(logFile, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, bufferSize: 4096);
            }

            return new StreamWriter(logStream);
        }

19 View Source File : LauncherUpdater.cs
License : GNU General Public License v3.0
Project Creator : AM2R-Community-Developers

public static void Main()
        {
            log.Info("Running update check...");

            string version = VERSION.Replace(".", "");

            //update section

            //delete old files that have been left
            if (File.Exists(CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak"))
            {
                log.Info("AM2RLauncher.bak detected. Removing file.");
                File.Delete(CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak");
            }
            if (currentPlatform.IsWinForms && File.Exists(oldConfigPath))
            {
                log.Info(CrossPlatformOperations.LAUNCHERNAME + ".oldCfg detected. Removing file.");
                File.Delete(oldConfigPath);
            }
            if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/oldLib"))
            {
                log.Info("Old lib folder detected, removing folder.");
                Directory.Delete(CrossPlatformOperations.CURRENTPATH + "/oldLib", true);
            }

            // Clean up old update libs
            if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/lib"))
            {
                foreach (FileInfo file in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetFiles())
                {
                    if (file.Name.EndsWith(".bak"))
                        file.Delete();
                }

                // Do the same for each subdir
                foreach (DirectoryInfo dir in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetDirectories())
                {
                    foreach (FileInfo file in dir.GetFiles())
                    {
                        if (file.Name.EndsWith(".bak"))
                            file.Delete();
                    }
                }
            }

            //check settings if autoUpdateLauncher is set to true
            bool autoUpdate = bool.Parse(CrossPlatformOperations.ReadFromConfig("AutoUpdateLauncher"));

            if (autoUpdate)
            {
                log.Info("AutoUpdate Launcher set to true!");

                //this is supposed to fix the updater throwing an exception on windows 7 and earlier(?)
                //see this for information: https://stackoverflow.com/questions/2859790/the-request-was-aborted-could-not-create-ssl-tls-secure-channel and https://stackoverflow.com/a/50977774
                if (currentPlatform.IsWinForms)
                {
                    ServicePointManager.Expect100Continue = true;
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                }

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest");
                HttpWebResponse response = null;
                try
                {        
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException)
                {
                    log.Error("WebException caught! Displaying MessageBox.");
                    MessageBox.Show(Language.Text.NoInternetConnection);
                    return;
                }

                Uri realUri = response.ResponseUri;
                string onlineVersion = realUri.AbsoluteUri.Substring(realUri.AbsoluteUri.LastIndexOf('/') + 1);
                bool isCurrentVersionOutdated = false;

                string[] localVersionArray = VERSION.Split('.');
                string[] onlineVersionArray = onlineVersion.Split('.');

                for (int i = 0; i < localVersionArray.Length; i++)
                {
                    if (int.Parse(onlineVersionArray[i]) > int.Parse(localVersionArray[i]))
                    {
                        isCurrentVersionOutdated = true;
                        break;
                    }
                }

                if (isCurrentVersionOutdated)
                {
                    log.Info("Current version (" + VERSION + ") is outdated! Initiating update for version " + onlineVersion + ".");

                    string tmpUpdatePath = CrossPlatformOperations.CURRENTPATH + "/tmpupdate/";
                    string zipPath = CrossPlatformOperations.CURRENTPATH + "/launcher.zip";

                    // Clean tmpupdate
                    if (Directory.Exists(tmpUpdatePath))
                        Directory.Delete(tmpUpdatePath);
                    if (!Directory.Exists(tmpUpdatePath))
                        Directory.CreateDirectory(tmpUpdatePath);

                    try
                    { 
                        using (var client = new WebClient())
                        {
                            string platformSuffix = "";
                            if (currentPlatform.IsWinForms) platformSuffix = "_win";
                            else if (currentPlatform.IsGtk) platformSuffix = "_lin";

                            log.Info("Downloading https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest/download/AM2RLauncher_" + onlineVersion + platformSuffix + ".zip to " + zipPath + ".");
                            
                            client.DownloadFile("https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest/download/AM2RLauncher_" + onlineVersion + platformSuffix + ".zip", zipPath);

                            log.Info("File successfully downloaded.");
                        }
                    }
                    catch(UnauthorizedAccessException)
                    {
                        log.Error("UnauthorizedAccessException caught! Displaying MessageBox.");
                        MessageBox.Show(Language.Text.UnauthorizedAccessMessage);
                        return;
                    }

                    ZipFile.ExtractToDirectory(zipPath, tmpUpdatePath);
                    log.Info("Updates successfully extracted to " + tmpUpdatePath);

                    File.Delete(zipPath);
                    File.Move(updatePath + "/" + CrossPlatformOperations.LAUNCHERNAME, CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak");
                    if (currentPlatform.IsWinForms) File.Move(CrossPlatformOperations.LAUNCHERNAME + ".config", CrossPlatformOperations.LAUNCHERNAME + ".oldCfg");

                    foreach (var file in new DirectoryInfo(tmpUpdatePath).GetFiles())
                    {
                        log.Info("Moving " +  file.FullName + " to " + CrossPlatformOperations.CURRENTPATH + "/" + file.Name);
                        File.Copy(file.FullName, updatePath + "/" + file.Name, true);
                    }
                    // for windows, the actual application is in "AM2RLauncher.dll". Which means, we need to update the lib folder as well.
                    if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/lib"))
                    {
                        // Directory.Move(CrossPlatformOperations.CURRENTPATH + "/lib", CrossPlatformOperations.CURRENTPATH + "/oldLib");
                        // So, because Windows behavior is dumb...

                        // Rename all files in lib to *.bak
                        foreach (FileInfo file in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetFiles())
                        {
                            file.CopyTo(file.Directory + file.Name + ".bak");
                        }

                        // Do the same for each subdir
                        foreach(DirectoryInfo dir in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetDirectories())
                        {
                            foreach (FileInfo file in dir.GetFiles())
                            {
                                file.CopyTo(file.Directory + file.Name + ".bak");
                            }
                        }

                        // Yes, the above calls could be recursive. No, I can't be bothered to make them as such.

                        HelperMethods.DirectoryCopy(tmpUpdatePath + "lib", CrossPlatformOperations.CURRENTPATH + "/lib", true);
                    }
                    
                    Directory.Delete(tmpUpdatePath, true);

                    CrossPlatformOperations.CopyOldConfigToNewConfig();

                    log.Info("Files extracted. Preparing to restart executable...");

                    if (currentPlatform.IsGtk) System.Diagnostics.Process.Start("chmod", "+x ./AM2RLauncher.Gtk");

                    System.Diagnostics.Process.Start(updatePath + "/" + CrossPlatformOperations.LAUNCHERNAME);
                    Environment.Exit(0);
                }
            }
            else
            {
                log.Info("AutoUpdate Launcher set to false. Exiting update check.");
            }
        }

19 View Source File : Injector.cs
License : MIT License
Project Creator : Akaion

private static string CreateTemporaryDll(byte[] dllBytes)
        {
            // Ensure a directory exists on disk to store the temporary DLL

            var temporaryDirectoryInfo = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "Bleak", "DLL"));

            // Clear the directory

            foreach (var file in temporaryDirectoryInfo.EnumerateFiles())
            {
                try
                {
                    file.Delete();
                }

                catch (Exception)
                {
                    // The file is currently open and cannot be safely deleted
                }
            }

            // Create a temporary DLL with a randomised name

            var temporaryDllPath = Path.Combine(temporaryDirectoryInfo.FullName, Path.GetRandomFileName() + ".dll");

            try
            {
                File.WriteAllBytes(temporaryDllPath, dllBytes);
            }

            catch (IOException)
            {
                // A DLL already exists with the specified name, is loaded in a process and cannot be safely overwritten
            }

            return temporaryDllPath;
        }

19 View Source File : Solution.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

private void DeleteFile(DirectoryInfo parentDirectory, string name)
        {
            FileInfo[] files = parentDirectory.GetFiles(name);
            foreach (FileInfo file in files)
            {
                try
                {
                    file.Delete();
                }
                catch (Exception)
                {
                }
            }
        }

19 View Source File : SftpWinForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int count = listView1.SelectedItems.Count;
            if (count == 1)
            {
                ListViewItem item = listView1.SelectedItems[0];
                Object tag = item.Tag;
                string path = getCurrDir() + item.Text;
                if (tag is FileInfo)
                {
                    FileInfo file = new FileInfo(path);
                    if (file.Exists)
                    {
                        file.Delete();
                    }
                }
                else if (tag is DirectoryInfo)
                {
                    DirectoryInfo dire = new DirectoryInfo(path);
                    if (dire.Exists)
                    {
                        dire.Delete(true);
                    }
                }

                ThreadPool.QueueUserWorkItem((a) =>
                {
                    Thread.Sleep(500);
                    RefreshFiles();
                });
            } 
        }

19 View Source File : util.cs
License : GNU Lesser General Public License v3.0
Project Creator : angturil

public static void EmptyDirectory(string directory, bool delete = true)
        {
            if (Directory.Exists(directory))
            {
                var directoryInfo = new DirectoryInfo(directory);
                foreach (System.IO.FileInfo file in directoryInfo.GetFiles()) file.Delete();
                foreach (System.IO.DirectoryInfo subDirectory in directoryInfo.GetDirectories()) subDirectory.Delete(true);

                if (delete) Directory.Delete(directory);
            }
        }

19 View Source File : FileSystemStorageService.cs
License : MIT License
Project Creator : akasarto

public virtual void Delete(string blobName)
		{
			blobName = blobName ?? string.Empty;
			var info = GetFileInfo(blobName);
			info.Delete();
		}

19 View Source File : FileHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public static void DeleteForce(
            string file)
        {
            if (!File.Exists(file))
            {
                return;
            }

            var fi = new FileInfo(file);

            if ((fi.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
            {
                fi.Attributes = FileAttributes.Normal;
            }

            fi.Delete();
        }

19 View Source File : ProjectSet.cs
License : MIT License
Project Creator : adamant

private static string PrepareCacheDir(Project project)
        {
            var cacheDir = Path.Combine(project.Path, ".forge-cache");
            Directory.CreateDirectory(cacheDir); // Ensure the cache directory exists

            // Clear the cache directory?
            var dir = new DirectoryInfo(cacheDir);
            foreach (var file in dir.EnumerateFiles())
                file.Delete();
            foreach (var subDirectory in dir.EnumerateDirectories())
                subDirectory.Delete(true);

            return cacheDir;
        }

19 View Source File : CompoundDoc.cs
License : Apache License 2.0
Project Creator : Appdynamics

[TestMethod, Ignore]
        public void Issue131()
        {
            var src = TempFile("report.xlsm");
            if (src.Exists) src.Delete();
            var package = new ExcelPackage(src);
            var sheets = Enumerable.Range(1, 500)   //460
                .Select(x => $"Sheet{x}");
            foreach (var sheet in sheets)
                package.Workbook.Worksheets.Add(sheet);

            package.Workbook.CreateVBAProject();
            package.Workbook.VbaProject.Modules.AddModule("Module1").Code
                = "\r\nPublic Sub SayHello()\r\nMsgBox(\"Hello\")\r\nEnd Sub\r\n";

            package.Save();
        }

19 View Source File : UpdatePriceSettings.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick

private void buttonPresetsDelete_Click(object sender, EventArgs e)
    {
      string name = comboBoxPresets.SelectedItem.ToString();
      if (MessageBox.Show("Are you sure you want to delete preset '" + name + "'? This cannot be undone.",
          "Delete preset", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
      {
        try
        {
          FileInfo f = new FileInfo(@".//Presets//" + name + ".xml");
          if (f.Exists) // better check, could have been deleted manually during the run
            f.Delete();
          presets.Remove(name);
          comboBoxPresets.Items.RemoveAt(comboBoxPresets.SelectedIndex);
          comboBoxPresets.SelectedIndex = comboBoxPresets.Items.Add("Choose Preset...");
          labelPresetsDescr.Text = "";
        }
        catch (Exception exc)
        {
          MKMHelpers.LogError("deleting preset", exc.Message, true);
        }
      }
    }

19 View Source File : Encrypt.cs
License : Apache License 2.0
Project Creator : Appdynamics

[TestMethod]
        [Ignore]
        public void EncrypTest()
        {
            var f = new FileInfo(@"c:\temp\encrwrite.xlsx");
            if (f.Exists)
            {
                f.Delete();
            }
            var p = new ExcelPackage(f);
            
            p.Workbook.Protection.SetPreplacedword("");
            p.Workbook.Protection.LockStructure = true;
            p.Encryption.Version = EncryptionVersion.Agile;

            var ws = p.Workbook.Worksheets.Add("Sheet1");
            for (int r = 1; r < 1000; r++)
            {
                ws.Cells[r, 1].Value = r;
            }
            p.Save();
        }

19 View Source File : AppConfig.cs
License : Apache License 2.0
Project Creator : 214175590

public void SaveConfig(int type = 0)
        {
            if(type == 0 || type == 1){
                try
                {
                    string mconfig = JsonConvert.SerializeObject(MConfig, Formatting.Indented);
                    if (!string.IsNullOrWhiteSpace(mconfig))
                    {
                        YSTools.YSFile.writeFileByString(MainForm.CONF_DIR + MC_NAME, mconfig, false, CONFIG_KEY);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("保存Main配置文件异常:" + ex.Message);
                    logger.Error("--->" + MC_NAME);
                }
            }

            if (type == 0 || type == 2)
            {
                string sconfig = null, scname = null;
                int index = 0;
                List<string> newFiles = new List<string>();
                foreach (KeyValuePair<string, SessionConfig> item in SessionConfigDict)
                {
                    try
                    {
                        sconfig = JsonConvert.SerializeObject(item.Value, Formatting.Indented);
                        if (!string.IsNullOrWhiteSpace(sconfig))
                        {
                            scname = string.Format("session{0}.json", index);
                            YSTools.YSFile.writeFileByString(MainForm.SESSION_DIR + scname, sconfig, false, CONFIG_KEY);
                            newFiles.Add(scname);
                            index++;
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error("保存Session配置文件异常:" + ex.Message);
                        logger.Error("--->" + item.Key);
                    }
                }

                DirectoryInfo dirs = new DirectoryInfo(MainForm.SESSION_DIR);
                FileInfo[] files = dirs.GetFiles();
                foreach(FileInfo file in files){
                    if (!newFiles.Contains(file.Name))
                    {
                        file.Delete();
                    }
                }
            }
            
        }

19 View Source File : Issues.cs
License : Apache License 2.0
Project Creator : Appdynamics

private void LoadData(FileInfo MyFile)
        {
            if (MyFile.Exists)
            {
                MyFile.Delete();  // ensures we create a new workbook
            }

            using (ExcelPackage EP = new ExcelPackage(MyFile))
            {
                // add a new worksheet to the empty workbook
                ExcelWorksheet wsData = EP.Workbook.Worksheets.Add("Data");
                //Add the headers
                wsData.Cells[1, 1].Value = "INVOICE_DATE";
                wsData.Cells[1, 2].Value = "TOTAL_INVOICE_PRICE";
                wsData.Cells[1, 3].Value = "EXTENDED_PRICE_VARIANCE";
                wsData.Cells[1, 4].Value = "AUDIT_LINE_STATUS";
                wsData.Cells[1, 5].Value = "RESOLUTION_STATUS";
                wsData.Cells[1, 6].Value = "COUNT";

                //Add some items...
                wsData.Cells["A2"].Value = Convert.ToDateTime("04/2/2012");
                wsData.Cells["B2"].Value = 33.63;
                wsData.Cells["C2"].Value = (-.87);
                wsData.Cells["D2"].Value = "Unfavorable Price Variance";
                wsData.Cells["E2"].Value = "Pending";
                wsData.Cells["F2"].Value = 1;

                wsData.Cells["A3"].Value = Convert.ToDateTime("04/2/2012");
                wsData.Cells["B3"].Value = 43.14;
                wsData.Cells["C3"].Value = (-1.29);
                wsData.Cells["D3"].Value = "Unfavorable Price Variance";
                wsData.Cells["E3"].Value = "Pending";
                wsData.Cells["F3"].Value = 1;

                wsData.Cells["A4"].Value = Convert.ToDateTime("11/8/2011");
                wsData.Cells["B4"].Value = 55;
                wsData.Cells["C4"].Value = (-2.87);
                wsData.Cells["D4"].Value = "Unfavorable Price Variance";
                wsData.Cells["E4"].Value = "Pending";
                wsData.Cells["F4"].Value = 1;

                wsData.Cells["A5"].Value = Convert.ToDateTime("11/8/2011");
                wsData.Cells["B5"].Value = 38.72;
                wsData.Cells["C5"].Value = (-5.00);
                wsData.Cells["D5"].Value = "Unfavorable Price Variance";
                wsData.Cells["E5"].Value = "Pending";
                wsData.Cells["F5"].Value = 1;

                wsData.Cells["A6"].Value = Convert.ToDateTime("3/4/2011");
                wsData.Cells["B6"].Value = 77.44;
                wsData.Cells["C6"].Value = (-1.55);
                wsData.Cells["D6"].Value = "Unfavorable Price Variance";
                wsData.Cells["E6"].Value = "Pending";
                wsData.Cells["F6"].Value = 1;

                wsData.Cells["A7"].Value = Convert.ToDateTime("3/4/2011");
                wsData.Cells["B7"].Value = 127.55;
                wsData.Cells["C7"].Value = (-10.50);
                wsData.Cells["D7"].Value = "Unfavorable Price Variance";
                wsData.Cells["E7"].Value = "Pending";
                wsData.Cells["F7"].Value = 1;

                using (var range = wsData.Cells[2, 1, 7, 1])
                {
                    range.Style.Numberformat.Format = "mm-dd-yy";
                }

                wsData.Cells.AutoFitColumns(0);
                EP.Save();
            }
        }

19 View Source File : SettingPresetStore.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick

private void buttonStore_Click(object sender, EventArgs e)
    {
      try
      {
        FileInfo f = new FileInfo(@".//Presets//" + textBoxFileName.Text + ".xml");
        if (f.Exists)
        {
          if (MessageBox.Show("Preset with this name already exists.\nOverwrite?", "Preset already exists",
              MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
            return;
        }
        toStore.Description = textBoxDescription.Text;
        // first try to write it into a memory stream to see if Save() finishes correctly
        // only if it does, delete the previous file (if there was one) and write into it
        MemoryStream ms = new MemoryStream();
        toStore.Serialize().Save(ms);
        if (f.Exists)
          f.Delete();
        FileStream fs = f.OpenWrite();
        ms.Position = 0;
        ms.CopyTo(fs);
        ms.Close();
        fs.Close();
        chosenName = textBoxFileName.Text;
        DialogResult = DialogResult.OK;
        Close();
      }
      catch (Exception exc)
      {
        MessageBox.Show("Saving preset to a file failed (make sure the name is a valid name for a file):"
            + Environment.NewLine + Environment.NewLine + exc.Message + Environment.NewLine,
            "Storing preset failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }

19 View Source File : deviceidmanager.cs
License : MIT License
Project Creator : Adoxio

public static ClientCredentials RegisterDevice(bool persist)
		{
			var persistValue = PersistToFile;

			PersistToFile = persist;

			if (persist)
			{
				// Kill an existing live device file.  RegisterDevice will create new file with new id and preplacedword values.

				var file = GetDeviceFile(null);

				if (file.Exists)
				{
					file.Delete();
				}
			}

			var userNameCredentials = GenerateDeviceUserName();
			
			var credentials = RegisterDevice(Guid.NewGuid(), null, userNameCredentials);

			PersistToFile = persistValue;

			return credentials;
		}

19 View Source File : Form2.cs
License : MIT License
Project Creator : 200Tigersbloxed

void InstallMulti()
        {
                statuslabel.Text = "Status: Preparing";
            progressBar1.Value = 10;
                allowinstalluninstall = false;
                currentlyinstallinguninstalling = true;
                button3.BackColor = SystemColors.GrayText;
                button4.BackColor = SystemColors.GrayText;
                Directory.CreateDirectory("Files");
                DirectoryInfo di = new DirectoryInfo("Files");
                foreach (FileInfo file in di.GetFiles())
                {
                    file.Delete();
                }
                foreach (DirectoryInfo dir in di.GetDirectories())
                {
                    dir.Delete(true);
                }
                Directory.CreateDirectory(@"Files\multiplayer");
                Directory.CreateDirectory(@"Files\dovr");
                Directory.CreateDirectory(@"Files\ca");
                Directory.CreateDirectory(@"Files\dc");
                Directory.CreateDirectory(@"Files\dep");
                statuslabel.Text = "Status: Downloading Multiplayer 1/6";
            progressBar1.Value = 20;
            using (var wc = new WebClient())
                {
                    wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadCompleted);
                    wc.DownloadProgressChanged += wc_DownloadProgressChanged;
                    if(multiselected == "a") {
                        if(File.Exists(bsl + @"\Plugins\BeatSaberMultiplayerLite.dll"))
                        {
                        statuslabel.Text = "Status: Failed";
                        allowinstalluninstall = true;
                        currentlyinstallinguninstalling = false;
                        button3.BackColor = SystemColors.MenuHighlight;
                        button4.BackColor = SystemColors.MenuHighlight;
                        MessageBox.Show("Beat Saber Multiplayer Lite is installed! Installation Failed. Please Uninstall Zingabopp's Multiplayer Lite to continue installing Andruzzzhka's Multiplayer", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            wc.DownloadFileAsync(new System.Uri("https://tigersserver.xyz/andruzzzhkalatest"), AppDomain.CurrentDomain.BaseDirectory + @"\Files\multiplayer.zip");
                        }
                    }
                    else if(multiselected == "z")
                    {
                        if (File.Exists(bsl + @"\Plugins\BeatSaberMultiplayer.dll"))
                        {
                        statuslabel.Text = "Status: Failed";
                        allowinstalluninstall = true;
                        currentlyinstallinguninstalling = false;
                        button3.BackColor = SystemColors.MenuHighlight;
                        button4.BackColor = SystemColors.MenuHighlight;
                        MessageBox.Show("Beat Saber Multiplayer is installed! Installation Failed. Please Uninstall Andruzzzhka's Multiplayer to continue installing Zingabopp's Multiplayer Lite", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            wc.DownloadFileAsync(new System.Uri("https://tigersserver.xyz/zingabopplatest"), AppDomain.CurrentDomain.BaseDirectory + @"\Files\multiplayer.zip");
                        }
                    }
                }
        }

19 View Source File : CentralServerConfigForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void downloadFile(string src, string dst)
        {
            try
            {
                FileInfo file = new FileInfo(dst);
                if (file.Exists)
                {
                    file.Delete();
                }
            }
            catch { }            
            monitorForm.getSftp().get(src, dst);
        }

19 View Source File : GameDataManager.cs
License : MIT License
Project Creator : 404Lcc

public void DeleteUserSetData()
        {
            if (UserSetDataExist())
            {
                FileInfo fileInfo = new FileInfo($"{PathUtil.GetPath(PathType.PersistentDataPath, "Res")}/UserSet.lcc");
                fileInfo.Delete();
                userSetData = null;
            }
        }

19 View Source File : File.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public void Create()
        {
            lock (locker)
            {
                if (info.Exists)
                {
                    info.Delete();
                }

                info.Create();
                using (StreamWriter writer = new StreamWriter(Path, false))
                {
                    writer.Write(string.Empty);
                }
            }
        }

19 View Source File : PackageUpdateHandler.cs
License : Apache License 2.0
Project Creator : Algoryx

private static void PostReload()
    {
      EditorApplication.LockReloadreplacedemblies();

      try {
        Debug.Log( "Verifying native libraries aren't loaded..." );
        {
          var processModules  = Process.GetCurrentProcess().Modules;
          var nativePluginsId = new DirectoryInfo( IO.Utils.AGXUnityPluginDirectory );
          foreach ( ProcessModule processModule in processModules ) {
            if ( processModule.FileName.Contains( nativePluginsId.FullName ) )
              throw new System.Exception( $"AGX Dynamics module {processModule.ModuleName} is loaded. Unable to install new version of package." );
          }
        }

        var packageName = string.Empty;
        foreach ( var arg in System.Environment.GetCommandLineArgs() ) {
          if ( arg.StartsWith( s_packageIdentifier ) )
            packageName = arg.Substring( s_packageIdentifier.Length );
        }

        if ( string.IsNullOrEmpty( packageName ) )
          throw new System.Exception( $"Unable to find package name identifier {s_packageIdentifier} in arguments list: " +
                                      string.Join( " ", System.Environment.GetEnvironmentVariables() ) );

        Debug.Log( "Removing old native binaries..." );
        foreach ( var nativePlugin in NativePlugins ) {
          var fi = new FileInfo( nativePlugin.replacedetPath );
          Debug.Log( $"    - {fi.Name}" );
          var fiMeta = new FileInfo( nativePlugin.replacedetPath + ".meta" );
          try {
            fi.Delete();
            if ( fiMeta.Exists )
              fiMeta.Delete();
          }
          catch ( System.Exception ) {
            Debug.LogError( "Fatal update error: Close Unity and remove AGX Dynamics for Unity directory and install the latest version." );
            throw;
          }
        }

        var newPackageFileInfo = new FileInfo( packageName );
        if ( newPackageFileInfo.Name.EndsWith( "_Plugins_x86_64.unitypackage" ) ) {
          // Manager is loaded when the binaries hasn't been added and ExternalAGXInitializer
          // pops up and asks if the user would like to located AGX Dynamics. We're
          // installing the binaries so it's a "user said no!" to begin with.
          ExternalAGXInitializer.UserSaidNo = true;

          var dataDirectory = IO.Utils.AGXUnityPluginDirectory +
                              Path.DirectorySeparatorChar +
                              "agx";
          if ( Directory.Exists( dataDirectory ) ) {
            var directoryHandler = new IO.DirectoryContentHandler( dataDirectory );
            Debug.Log( $"Removing AGX Dynamics data directory {directoryHandler.RootDirectory}..." );
            directoryHandler.DeleteAllCollected();
          }
        }
        else {
          Debug.Log( "Removing all non-user specific content..." );
          IO.DirectoryContentHandler.DeleteContent();
        }

        // This will generate compile errors from scripts using AGXUnity and
        // we don't know how to hide these until we're done, mainly because
        // we have no idea when we're done with the update.
        // 
        // If this isn't performed, the compiler will throw exception due
        // to missing references and Unity will crash the first time we
        // use AGX Dynamics.
        replacedetDatabase.Refresh();

        Debug.Log( $"Starting import of package: {packageName}" );
        replacedetDatabase.ImportPackage( packageName, false );
      }
      catch ( System.Exception e ) {
        Debug.LogException( e );
      }

      Build.DefineSymbols.Remove( Build.DefineSymbols.ON_AGXUNITY_UPDATE );
      EditorApplication.UnlockReloadreplacedemblies();
    }

See More Examples