System.IO.DirectoryInfo.Create()

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

758 Examples 7

19 Source : OutputImageUtil.cs
with GNU General Public License v3.0
from 0xC0000054

public static void SaveAllToFolder(IReadOnlyList<Surface> outputImages, string outputFolder)
        {
            if (outputImages is null)
            {
                ExceptionUtil.ThrowArgumentNullException(nameof(outputImages));
            }

            if (outputFolder is null)
            {
                ExceptionUtil.ThrowArgumentNullException(nameof(outputFolder));
            }

            DirectoryInfo directoryInfo = new DirectoryInfo(outputFolder);

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

            string currentTime = DateTime.Now.ToString("yyyyMMdd-THHmmss");

            for (int i = 0; i < outputImages.Count; i++)
            {
                string imageName = string.Format(CultureInfo.InvariantCulture, "{0}-{1}.png", currentTime, i);

                string path = Path.Combine(outputFolder, imageName);

                using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    using (System.Drawing.Bitmap image = outputImages[i].CreateAliasedBitmap())
                    {
                        image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                    }
                }
            }
        }

19 Source : Utils.cs
with Apache License 2.0
from 214175590

public static void createParentDir(DirectoryInfo dire)
        {
            if(!dire.Exists){
                if(dire.Parent.Exists){
                    dire.Create();
                }
                else
                {
                    createParentDir(dire.Parent);
                }
            }
        }

19 Source : SftpWinForm.cs
with Apache License 2.0
from 214175590

private void newFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InputForm form = new InputForm("请输入文件夹名称", "", new InputForm.FormResult((name) =>
            {
                if (!string.IsNullOrWhiteSpace(name))
                {
                    DirectoryInfo dire = new DirectoryInfo(getCurrDir() + name);
                    if(!dire.Exists){
                        dire.Create();
                    }
                    else
                    {
                        MessageBox.Show(this, "目录已存在");
                    }

                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        RefreshFiles();
                    });
                }
                else
                {
                    MessageBox.Show(this, "名称不能为空");
                }
            }));
            form.ShowDialog(this);
        }

19 Source : FileManager.cs
with GNU General Public License v3.0
from 2dust

public static bool ZipExtractToFullFile(string fileName)
        {
            try
            {
                using (ZipArchive archive = ZipFile.OpenRead(fileName))
                {
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        if (entry.Length == 0)
                            continue;

                        string entryOuputPath = Utils.GetPath(entry.FullName);
                        FileInfo fileInfo = new FileInfo(entryOuputPath);
                        fileInfo.Directory.Create();
                        entry.ExtractToFile(entryOuputPath, true);
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                return false;
            }
            return true;
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from 2dust

private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                Process[] existing = Process.GetProcessesByName("v2rayN");
                foreach (Process p in existing)
                {
                    string path = p.MainModule.FileName;
                    if (path == GetPath("v2rayN.exe"))
                    {
                        p.Kill();
                        p.WaitForExit(100);
                    }
                }
            }
            catch (Exception ex)
            {
                // Access may be denied without admin right. The user may not be an administrator.
                showWarn("Failed to close v2rayN(关闭v2rayN失败).\n" +
                    "Close it manually, or the upgrade may fail.(请手动关闭正在运行的v2rayN,否则可能升级失败。\n\n" + ex.StackTrace);
            }

            StringBuilder sb = new StringBuilder();
            try
            {
                if (!File.Exists(fileName))
                {
                    if (File.Exists(defaultFilename))
                    {
                        fileName = defaultFilename;
                    }
                    else
                    {
                        showWarn("Upgrade Failed, File Not Exist(升级失败,文件不存在).");
                        return;
                    }
                }

                string thisAppOldFile = Application.ExecutablePath + ".tmp";
                File.Delete(thisAppOldFile);
                string startKey = "v2rayN/";


                using (ZipArchive archive = ZipFile.OpenRead(fileName))
                {
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        try
                        {
                            if (entry.Length == 0)
                            {
                                continue;
                            }
                            string fullName = entry.FullName;
                            if (fullName.StartsWith(startKey))
                            {
                                fullName = fullName.Substring(startKey.Length, fullName.Length - startKey.Length);
                            }
                            if (Application.ExecutablePath.ToLower() == GetPath(fullName).ToLower())
                            {
                                File.Move(Application.ExecutablePath, thisAppOldFile);
                            }

                            string entryOuputPath = GetPath(fullName);

                            FileInfo fileInfo = new FileInfo(entryOuputPath);
                            fileInfo.Directory.Create();
                            entry.ExtractToFile(entryOuputPath, true);
                        }
                        catch (Exception ex)
                        {
                            sb.Append(ex.StackTrace);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                showWarn("Upgrade Failed(升级失败)." + ex.StackTrace);
                return;
            }
            if (sb.Length > 0)
            {
                showWarn("Upgrade Failed,Hold ctrl + c to copy to clipboard.\n" +
                    "(升级失败,按住ctrl+c可以复制到剪贴板)." + sb.ToString());
                return;
            }

            Process.Start("v2rayN.exe");
            MessageBox.Show("Upgrade successed(升级成功)", "", MessageBoxButtons.OK, MessageBoxIcon.Information);

            Close();
        }

19 Source : CmdLineActions.cs
with MIT License
from action-bi-toolkit

[ArgActionMethod, ArgShortcut("compile-pbix"), ArgDescription("Generates a PBIX/PBIT file from sources in the specified PbixProj folder. Currently, the PBIX output is supported only for report-only projects (\"thin\" reports), and PBIT for projects containing a data model.")]
        public void CompilePbix(
            [ArgRequired, ArgExistingDirectory, ArgDescription("The PbixProj folder to generate the PBIX from.")] string folder,
            [ArgDescription("The path for the output file. If not provided, creates the file in the current working directory, using the foldername. A directory or file name can be provided. The full output path is created if it does not exist.")]
                string outPath,
            [ArgDescription("The target file format."), ArgDefaultValue(PbiFileFormat.PBIX)] PbiFileFormat format,
            [ArgDescription("Overwrite the destination file if it already exists, fail otherwise.")] bool overwrite
        )
        {
            // format: pbix, pbit
            // mode: Create, Merge
            // mashupHandling: Auto, Skip, GenerateFromModel, FromFolder

            // SUCCESS
            // [x] PBIX from Report-Only
            // [x] PBIT from PBIT sources (incl Mashup)
            // [x] PBIT from PBIX sources (no mashup)
            //
            // TODO
            // [ ] PBIX from source with model
            // [ ] Merge into PBIX

            FileInfo outputFile;

            var filenameFromPbixProj = $"{new DirectoryInfo(folder).Name}.{(format == PbiFileFormat.PBIT ? "pbit" : "pbix")}";

            if (String.IsNullOrEmpty(outPath))
                outputFile = new FileInfo(filenameFromPbixProj);
            else 
            {
                var pathAsDirectory = new DirectoryInfo(outPath);
                var pathAsFile = new FileInfo(outPath);

                if (pathAsFile.Exists)
                    /* Existing File */
                    outputFile = pathAsFile;

                else if (pathAsDirectory.Exists)
                    /* Existing Directory: Use generated filename */
                    outputFile = new FileInfo(Path.Combine(pathAsDirectory.FullName, filenameFromPbixProj));
                
                else if (!String.IsNullOrEmpty(pathAsFile.Extension))
                    /* Path with extension provided: Use as file path */
                    outputFile = pathAsFile;
                
                else
                    /* Path w/o extension provided: Use as directory, generate filename */
                    outputFile = new FileInfo(Path.Combine(pathAsDirectory.FullName, filenameFromPbixProj));
            }

            if (outputFile.Exists && !overwrite)
                throw new PbiToolsCliException(ExitCode.FileExists, $"Destination file '{outputFile.FullName}' exists and the '-overwrite' option was not specified.");

            using (var proj = PbiTools.Model.PbixModel.FromFolder(folder))
            {
                outputFile.Directory.Create();

                proj.ToFile(outputFile.FullName, format, _dependenciesResolver);
            }

            Log.Information("{Format} file written to: {Path}", format, outputFile.FullName);
        }

19 Source : IOUtilL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void DeleteDirectory_DeletesReadOnlyDirectories()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory with a read-only subdirectory.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                string subdirectory = Path.Combine(directory, "some subdirectory");
                try
                {
                    var subdirectoryInfo = new DirectoryInfo(subdirectory);
                    subdirectoryInfo.Create();
                    subdirectoryInfo.Attributes = subdirectoryInfo.Attributes | FileAttributes.ReadOnly;

                    // Act.
                    IOUtil.DeleteDirectory(directory, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(directory));
                }
                finally
                {
                    // Cleanup.
                    var subdirectoryInfo = new DirectoryInfo(subdirectory);
                    if (subdirectoryInfo.Exists)
                    {
                        subdirectoryInfo.Attributes = subdirectoryInfo.Attributes & ~FileAttributes.ReadOnly;
                    }

                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

19 Source : IOUtilL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void DeleteDirectory_DeletesReadOnlyRootDirectory()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a read-only directory.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    var directoryInfo = new DirectoryInfo(directory);
                    directoryInfo.Create();
                    directoryInfo.Attributes = directoryInfo.Attributes | FileAttributes.ReadOnly;

                    // Act.
                    IOUtil.DeleteDirectory(directory, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(directory));
                }
                finally
                {
                    // Cleanup.
                    var directoryInfo = new DirectoryInfo(directory);
                    if (directoryInfo.Exists)
                    {
                        directoryInfo.Attributes = directoryInfo.Attributes & ~FileAttributes.ReadOnly;
                        directoryInfo.Delete();
                    }
                }
            }
        }

19 Source : UploadController.cs
with MIT License
from ADefWebserver

private static void DeleteFiles(string FilePath)
        {            
            if (System.IO.Directory.Exists(FilePath))
            {
                DirectoryInfo Directory = new DirectoryInfo(FilePath);
                Directory.Delete(true);
                Directory.Create();
            }
        }

19 Source : deviceidmanager.cs
with MIT License
from Adoxio

private static void WriteDevice(string environment, LiveDevice device)
		{
			FileInfo file = GetDeviceFile(environment);
			if (!file.Directory.Exists)
			{
				file.Directory.Create();
			}

			using (FileStream stream = file.Open(FileMode.CreateNew, FileAccess.Write, FileShare.None))
			{
				Serialize(stream, device);
			}
		}

19 Source : FileSystemStorageService.cs
with MIT License
from akasarto

public virtual void WriteStream(string blobName, Stream blobStream)
		{
			blobName = blobName ?? throw new ArgumentNullException(nameof(blobName), nameof(FileSystemStorageService));
			blobStream = blobStream ?? throw new ArgumentNullException(nameof(blobStream), nameof(FileSystemStorageService));

			var fileInfo = GetFileInfo(blobName);

			if (!fileInfo.Directory.Exists)
			{
				fileInfo.Directory.Create();
			}

			using (blobStream)
			{
				using (var fStream = fileInfo.OpenWrite())
				{
					blobStream.CopyTo(fStream);
				}
			}
		}

19 Source : SettingStore.cs
with Apache License 2.0
from AKruimink

public void Save<TSetting>(TSetting settings)
        {
            var file = Path.Combine(_filePath, $"{typeof(TSetting).Name}.json");
            var fileInfo = new FileInfo(file);
            fileInfo.Directory.Create();

            var serializerOptions = new JsonSerializerOptions
            {
                WriteIndented = true
            };
            var json = JsonSerializer.Serialize(settings, serializerOptions);
            File.WriteAllText(file, json);
        }

19 Source : LoggerConfigurationExtensions.cs
with Apache License 2.0
from alaatm

public static LoggerConfiguration Sejil(
            this LoggerSinkConfiguration loggerConfiguration,
            ISejilSettings settings,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum)
        {
            try
            {
                var sqliteDbFile = new FileInfo(settings.SqliteDbPath);
                sqliteDbFile.Directory.Create();

                return loggerConfiguration.Sink(
                    new SejilSink(settings),
                    restrictedToMinimumLevel);
            }
            catch (Exception ex)
            {
                SelfLog.WriteLine(ex.Message);
                throw;
            }
        }

19 Source : DirectoryOptions.cs
with MIT License
from AlexanderFroemmgen

public void CopyDirectoryRecursively(DirectoryInfo fromDi, string destPath)
        {
            new DirectoryInfo(destPath).Create();

            foreach (var dirEntry in fromDi.GetDirectories())
            {
                var tmpDestPath = destPath + "/" + dirEntry.Name;

                new DirectoryInfo(tmpDestPath).Create();
                CopyDirectoryRecursively(dirEntry, tmpDestPath);
            }

            foreach (var dirEntry in fromDi.GetFiles())
            {
                dirEntry.CopyTo(destPath + "/" + dirEntry.Name);
            }
        }

19 Source : ExperimentFileController.cs
with MIT License
from AlexanderFroemmgen

[HttpPost]
        public IActionResult Create([FromBody] ExperimentFileDto requestData)
        {

            var dirname = relativeFolder + "/" + requestData.Name;
            var configDirname = dirname + "/configurations/";
            var filename = dirname + "/script.py";
            var filenameInstall = dirname + "/install.py";

            if (isValidPath(filename)) {
                new DirectoryInfo(dirname).Create();
                new DirectoryInfo(configDirname).Create();

                Repository.Init(dirname);

                _directoryOptions.SetFileContents(filename, requestData.Script);
                _directoryOptions.SetFileContents(filenameInstall, requestData.ScriptInstall);
                _directoryOptions.SetFileContents(configDirname + requestData.Configurations.First().Key + ".json", requestData.Configurations.First().Value);

                /* generate experiment framework file... */
                var frameworkFolder = new DirectoryInfo(dirname + "/framework");
                if(!frameworkFolder.Exists)
                {
                    frameworkFolder.Create();
                }

                GitIntegration.CreateBackup(dirname, "create/update experimentTemplate", _gitRemoteOptions);
                return Ok();
            }
            else
            {
                return BadRequest("Invalid name.");
            }
        }

19 Source : ExperimentFrameworkController.cs
with MIT License
from AlexanderFroemmgen

private void ensureDirectoryExists(string path)
        {
            var di = new DirectoryInfo(path);
            if (!di.Exists)
            {
                di.Create();
            }
        }

19 Source : ExperimentController.cs
with MIT License
from AlexanderFroemmgen

private void CreatePersistentSnapshotFolder(Experiment experiment)
        {
            // TODO: In case a file exists in the general and the specific framework folder, we get an exception.

            var targetFolder = _directoryOptions.DataLocation + $"/Experiments/sim{experiment.Id:0000}";
            var di = new DirectoryInfo(targetFolder);
            if(di.Exists)
            {
                di.MoveTo(_directoryOptions.DataLocation + $"/Experiments/sim{experiment.Id:0000}_removed_at_{DateTime.Now:ddMMyy_Hmmss}");
                di = new DirectoryInfo(targetFolder);
            }

            di.Create();

            /* general experiment files */
            var fileNameGeneral = _directoryOptions.DataLocation + "/ExperimentFramework";
            
            foreach (var fileEntry in new DirectoryInfo(fileNameGeneral).GetFiles())
            {
                fileEntry.CopyTo(targetFolder + "/" + fileEntry.Name);
            }

            /* files for this experiment fileName */
            var fileName = _directoryOptions.DataLocation + "/ExperimentTemplates/" + experiment.FileName + "/framework";
            _directoryOptions.CopyDirectoryRecursively(new DirectoryInfo(fileName), targetFolder);
        }

19 Source : ExperimentInstanceController.cs
with MIT License
from AlexanderFroemmgen

[HttpPost("binaryfiles/{filename}")]
        public IActionResult AddBinaryFile([FromHeader(Name = "Worker-Token")] string token, string filename)
        {
            var di_experiment = new DirectoryInfo(_directoryOptions.DataLocation + "/binary_files/" + 
                _currentExperimentInstance.Experiment.Id);

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

            var di_experiment_instance = new DirectoryInfo(_directoryOptions.DataLocation + "/binary_files/" + 
                _currentExperimentInstance.Experiment.Id + "/" + _currentExperimentInstance.Id);
            if (!di_experiment_instance.Exists)
            {
                di_experiment_instance.Create();
            }

            var destFile = _directoryOptions.DataLocation + "/binary_files/" +
                _currentExperimentInstance.Experiment.Id + "/" + _currentExperimentInstance.Id + "/" + filename;

            using (var fs = new FileStream(destFile, FileMode.Create, FileAccess.Write))
            {
                Request.Body.CopyTo(fs);
            }

            return Ok();
        }

19 Source : Startup.cs
with MIT License
from AlexanderFroemmgen

private void EnsureDataLocationAvailable(string location, DirectoryOptions directoryOptions)
        {
            var di = new DirectoryInfo(location);
            if(!di.Exists)
            {
                di.Create();

                /* Copy existing examples to this location */
                directoryOptions.CopyDirectoryRecursively(new DirectoryInfo("AppData/ExperimentTemplates"), location + "/ExperimentTemplates");
                directoryOptions.CopyDirectoryRecursively(new DirectoryInfo("AppData/ExperimentFramework"), location + "/ExperimentFramework");
            }
        }

19 Source : PluginManager.cs
with MIT License
from AlexMog

private void _loadPlugins()
        {
            var pluginsDirectory = new DirectoryInfo(_pluginsPath);

            if (!pluginsDirectory.Exists)
            {
                pluginsDirectory.Create();
            }
            
            foreach (var file in pluginsDirectory.GetFiles("*.dll"))
            {
                var replacedembly = replacedembly.LoadFrom(file.FullName);
                foreach (var type in replacedembly.GetTypes())
                {
                    if (!type.IsSubclreplacedOf(typeof(IPlugin)) || type.IsAbstract) continue;
                    Longship.Instance.Log.LogInfo($"Loading plugin {file.Name}...");
                    try
                    {
                        _plugins[type] = new LoadedPlugin()
                        {
                            Plugin = type.InvokeMember(
                                null,
                                BindingFlags.CreateInstance,
                                null,
                                null,
                                null) as IPlugin,
                            Name = file.Name
                        };
                    }
                    catch (Exception e)
                    {
                        Longship.Instance.Log.LogError($"Can't load plugin {file.Name}.");
                        Longship.Instance.Log.LogError(e);
                    }
                }
            }
        }

19 Source : BuildProcessCallbacksHandler.cs
with Apache License 2.0
from Algoryx

public static void CopyDirectory( DirectoryInfo source, DirectoryInfo destination )
    {
      if ( !destination.Exists )
        destination.Create();

      foreach ( var fileInfo in source.GetFiles() )
        fileInfo.CopyTo( Path.Combine( destination.FullName, fileInfo.Name ), true );

      foreach ( var directoryInfo in source.GetDirectories() )
        CopyDirectory( directoryInfo, new DirectoryInfo( Path.Combine( destination.FullName, directoryInfo.Name ) ) );
    }

19 Source : ConfigController.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[HttpPost]
        public void SetServiceConfig(string org, string app, [FromBody] dynamic serviceConfig)
        {
            string serviceConfigPath = _settings.GetServicePath(org, app, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)) + _settings.ServiceConfigFileName;
            ServiceConfiguration serviceConfigurationObject = null;

            if (System.IO.File.Exists(serviceConfigPath))
            {
                string serviceConfiguration = System.IO.File.ReadAllText(serviceConfigPath, Encoding.UTF8);
                serviceConfigurationObject = JsonConvert.DeserializeObject<ServiceConfiguration>(serviceConfiguration);
                serviceConfigurationObject.ServiceDescription = serviceConfig.serviceDescription.ToString();
                serviceConfigurationObject.ServiceId = serviceConfig.serviceId.ToString();
                serviceConfigurationObject.ServiceName = serviceConfig.serviceName.ToString();
            }
            else
            {
                new FileInfo(serviceConfigPath).Directory.Create();
                serviceConfigurationObject = new ServiceConfiguration()
                {
                    RepositoryName = app,
                    ServiceDescription = serviceConfig.serviceDescription.ToString(),
                    ServiceId = serviceConfig.serviceId.ToString(),
                    ServiceName = serviceConfig.serviceName.ToString()
                };
            }

            System.IO.File.WriteAllText(serviceConfigPath, JObject.FromObject(serviceConfigurationObject).ToString(), Encoding.UTF8);
            _repository.UpdateServiceInformationInApplication(org, app, serviceConfigurationObject);
        }

19 Source : ControlPanel.cs
with MIT License
from AmigoCap

void ExportJson() {
            UpdateDataFromUI();

            string path = "";

            try {
                dataInfo.Directory.Create();
                path = System.IO.Path.Combine(workingDirectory, "export.json");
                using (StreamWriter w = new StreamWriter(path)) {
                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    settings.FloatFormatHandling = FloatFormatHandling.String;
                    settings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                    w.Write(JsonConvert.SerializeObject(data, Formatting.Indented, settings));
                }
            }
            catch (System.Exception e) {
                MakeErrorWindow("Error exporting .json: ensure export.json is not being used by another process\n\n" + e.Message);
            }

            MakeMessageWindow(".json export", "Succesfully exported configuration to " + path);
        }

19 Source : loading.cs
with MIT License
from Amine-Smahi

private void t_Tick(object sender, EventArgs e)
        {
            g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            var myBrush = new SolidBrush(Color.FromArgb(37, 155, 36));
            g.FillRectangle(myBrush, new Rectangle(0, 0, (int) (pbComplete * pbUnit), pbHEIGHT));


            if (pbComplete == 60)
            {

                FileInfo fi = new FileInfo(@".\a\lang.txt");
                DirectoryInfo di = new DirectoryInfo(@".\a");
                if (!di.Exists)
                {
                    di.Create();
                }
                if (!fi.Exists)
                {
                    fi.Create().Dispose();
                }

                /* if (!File.Exists(path))
                 {
                     File.Create(path).Dispose();
                     using (TextWriter tw = new StreamWriter(path))
                     {
                         tw.WriteLine("english");
                         tw.Close();
                     }
                 }
                 */
            }

            if (pbComplete == 70)
                if (File.Exists(path))
                    using (TextReader tr = new StreamReader(path))
                    {
                        var langugeChoused = tr.ReadLine();

                        if (langugeChoused == "arabic")
                        {
                            fom.bunifuTileButton1.LabelText = "إفتح صورة";
                            fom.bunifuTileButton2.LabelText = "إحفظ الصورة";
                            fom.bunifuTileButton3.LabelText = "أكتب الرسالة";
                            fom.bunifuTileButton4.LabelText = "أظهر الصورة";
                            fom.about_us.LabelText = "عن البرنامج";
                            fom.bunifuTileButton6.LabelText = "إعداداتي";
                        }
                    }

            picboxPB.Image = bmp;
            pbComplete++;

            if (pbComplete > 100)
            {
                g.Dispose();
                t.Stop();
                Hide();

                fom.Show();
            }
        }

19 Source : Solution.cs
with GNU General Public License v3.0
from AndreiFedarets

public bool UpdateExternals(IOutput output, Configuration configuration, bool force, string msbuildPath = null)
        {
            foreach (SolutionDependency solutionDependency in _dependencies)
            {
                Solution solution = _solutions.GetByChronosSolutioName(solutionDependency.SolutionName);
                foreach (FileDependency fileDependency in solutionDependency.Files)
                {
                    FileInfo sourceFile = solution.GetBuildFile(fileDependency.Name, configuration);
                    FileInfo targetFile = GetExternalsFile(fileDependency.Name, configuration);
                    if ((!targetFile.Exists && !sourceFile.Exists) || force)
                    {
                        if (!solution.BuildSolution(output, configuration, force, msbuildPath))
                        {
                            return false;
                        }
                        return UpdateExternals(output, configuration, false, msbuildPath);
                    }
                    //if target file doesn't exist or it's last write less that source file write time
                    //then we should copy source to target
                    if (!targetFile.Exists || sourceFile.LastWriteTimeUtc > targetFile.LastWriteTimeUtc)
                    {
                        if (!targetFile.Directory.Exists)
                        {
                            targetFile.Directory.Create();
                        }
                        sourceFile.CopyTo(targetFile.FullName, true);
                    }
                }
            }
            return true;
        }

19 Source : CrashLogger.cs
with GNU General Public License v3.0
from AndreiFedarets

public static void Setup(ICrashDumpSettings settings)
        {
            if (!settings.IsEnabled)
            {
                return;
            }
            DirectoryInfo dumpsDirectory = settings.DumpsDirectory.GetDirectory();
            if (!dumpsDirectory.Exists)
            {
                dumpsDirectory.Create();
            }
            AgentLibrary library = new AgentLibrary();
            library.SetupCrashDumpLogger(dumpsDirectory.FullName);
        }

19 Source : FileLogger.cs
with GNU General Public License v3.0
from AndreiFedarets

internal override void Initialize(ILoggerSettings settings, string applicationName)
        {
            base.Initialize(settings, applicationName);
            _logsDirectory = ((IFileLoggerSettings)settings).LogsDirectory.GetDirectory();
            if (!_logsDirectory.Exists)
            {
                _logsDirectory.Create();
            }
        }

19 Source : Config.cs
with MIT License
from andruzzzhka

public static bool Load()
        {
            if (_instance != null) return false;
            try
            {
                FileLocation.Directory.Create();
                Plugin.log.Debug($"Attempting to load JSON @ {FileLocation.FullName}");
                _instance = JsonUtility.FromJson<Config>(File.ReadAllText(FileLocation.FullName));

                UpdateModVersion(_instance);

                _instance.MarkDirty();
                _instance.Save();
            }
            catch (Exception)
            {
                Plugin.log.Error($"Unable to load config @ {FileLocation.FullName}");
                return false;
            }
            return true;
        }

19 Source : Config.cs
with MIT License
from andruzzzhka

public static bool Create()
        {
            if (_instance != null) return false;
            try
            {
                FileLocation.Directory.Create();
                Plugin.log.Info($"Creating new config @ {FileLocation.FullName}");
                Instance.Save();
            }
            catch (Exception)
            {
                Plugin.log.Error($"Unable to create new config @ {FileLocation.FullName}");
                return false;
            }
            return true;
        }

19 Source : Logger.cs
with MIT License
from andruzzzhka

FileInfo GetPath() {
            var logsDir = new DirectoryInfo($"./{Settings.Instance.Logger.LogsDir}/{DateTime.Now:dd-MM-yy}");
            logsDir.Create();
            
            if (logsDir.GetFiles().Length > 0)
            {
                if (string.IsNullOrEmpty(File.ReadAllText($"{logsDir.FullName}/{logsDir.GetFiles().Length - 1}.txt")))
                {
                    return new FileInfo($"{logsDir.FullName}/{logsDir.GetFiles().Length - 1}.txt");
                }
            }
            return new FileInfo($"{logsDir.FullName}/{logsDir.GetFiles().Length}.txt");
        }

19 Source : FileHelper.cs
with MIT License
from AnotherEnd15

public static void CopyDirectory(string srcDir, string tgtDir)
		{
			DirectoryInfo source = new DirectoryInfo(srcDir);
			DirectoryInfo target = new DirectoryInfo(tgtDir);
	
			if (target.FullName.StartsWith(source.FullName, StringComparison.CurrentCultureIgnoreCase))
			{
				throw new Exception("父目录不能拷贝到子目录!");
			}
	
			if (!source.Exists)
			{
				return;
			}
	
			if (!target.Exists)
			{
				target.Create();
			}
	
			FileInfo[] files = source.GetFiles();
	
			for (int i = 0; i < files.Length; i++)
			{
				File.Copy(files[i].FullName, Path.Combine(target.FullName, files[i].Name), true);
			}
	
			DirectoryInfo[] dirs = source.GetDirectories();
	
			for (int j = 0; j < dirs.Length; j++)
			{
				CopyDirectory(dirs[j].FullName, Path.Combine(target.FullName, dirs[j].Name));
			}
		}

19 Source : DirectoryHelper.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public static void DirectoryCopy(string sourcePath, string destinationPath)
        {
            var sourceDirectory = new DirectoryInfo(sourcePath);
            var destinationDirectory = new DirectoryInfo(destinationPath);

            if (destinationDirectory.Exists == false)
            {
                destinationDirectory.Create();
                destinationDirectory.Attributes = sourceDirectory.Attributes;
            }

            foreach (FileInfo fileInfo in sourceDirectory.GetFiles())
            {
                fileInfo.CopyTo(destinationDirectory.FullName + @"\" + fileInfo.Name, true);
            }

            foreach (DirectoryInfo directoryInfo in sourceDirectory.GetDirectories())
            {
                DirectoryCopy(directoryInfo.FullName, destinationDirectory.FullName + @"\" + directoryInfo.Name);
            }
        }

19 Source : VBA.cs
with Apache License 2.0
from Appdynamics

[Ignore]
        [TestMethod]
        public void VbaError()
        {
            DirectoryInfo workingDir = new DirectoryInfo(@"C:\epplusExample\folder");
            if (!workingDir.Exists) workingDir.Create();
            FileInfo f = new FileInfo(workingDir.FullName + "//" + "temp.xlsx");
            if (f.Exists) f.Delete();
            ExcelPackage myPackage = new ExcelPackage(f);
            myPackage.Workbook.CreateVBAProject();
            ExcelWorksheet excelWorksheet = myPackage.Workbook.Worksheets.Add("Sheet1");
            ExcelWorksheet excelWorksheet2 = myPackage.Workbook.Worksheets.Add("Sheet2");
            ExcelWorksheet excelWorksheet3 = myPackage.Workbook.Worksheets.Add("Sheet3");
            FileInfo f2 = new FileInfo(workingDir.FullName + "//" + "newfile.xlsm");
            ExcelVBAModule excelVbaModule = myPackage.Workbook.VbaProject.Modules.AddModule("Module1");
            StringBuilder mybuilder = new StringBuilder(); mybuilder.AppendLine("Sub Jiminy()");
            mybuilder.AppendLine("Range(\"D6\").Select");
            mybuilder.AppendLine("ActiveCell.FormulaR1C1 = \"Jiminy\"");
            mybuilder.AppendLine("End Sub");
            excelVbaModule.Code = mybuilder.ToString();
            myPackage.SaveAs(f2);
            myPackage.Dispose();
        }

19 Source : Utils.cs
with Apache License 2.0
from Appdynamics

internal static DirectoryInfo GetDirectoryInfo(string directory)
        {
            var di = new DirectoryInfo(_outputDir.FullName + Path.DirectorySeparatorChar + directory);
            if (!di.Exists)
            {
                di.Create();
            }
            return di;
        }

19 Source : XmlSettingsFormat.cs
with MIT License
from Aragas

public override bool Save(BaseSettings settings, string directoryPath, string filename)
        {
            var path = Path.Combine(directoryPath, filename + ".xml");

            var content = SaveJson(settings);
            var xmlDoreplacedent = JsonConvert.DeserializeXmlNode(content, settings is IWrapper wrapper1 ? wrapper1.Object.GetType().Name : settings.GetType().Name);

            var file = new FileInfo(path);
            file.Directory?.Create();
            var writer = file.CreateText();
            xmlDoreplacedent.Save(writer);
            writer.Dispose();

            return true;
        }

19 Source : BaseJsonSettingsFormat.cs
with MIT License
from Aragas

public virtual bool Save(BaseSettings settings, string directoryPath, string filename)
        {
            var path = Path.Combine(directoryPath, filename + ".json");

            var content = SaveJson(settings);

            var file = new FileInfo(path);
            file.Directory?.Create();
            var writer = file.CreateText();
            writer.Write(content);
            writer.Dispose();

            return true;
        }

19 Source : Program.cs
with MIT License
from Arefu

[STAThread]
        private static void Main(string[] Args)
        {
            var UseArgs = false;
            var TocFileLocation = "";

            if (Args.Length > 0)
            {
                TocFileLocation = Args.FirstOrDefault(File.Exists);
                if (TocFileLocation != null)
                    UseArgs = true;
                else
                    Utilities.Log("Coun't Find TOC File.", Utilities.Event.Warning);
            }

            Console.replacedle = "Onomatopaira";

            using (var FileDialog = new OpenFileDialog())
            {
                FileDialog.replacedle = "Open Yu-Gi-Oh TOC File...";
                FileDialog.Filter = "Yu-Gi-Oh! Wolf TOC File |*.toc";
                if (UseArgs == false)
                {
                    if (FileDialog.ShowDialog() != DialogResult.OK) return;
                    TocFileLocation = FileDialog.FileName;
                }

                try
                {
                    using (var reader = new StreamReader(TocFileLocation))
                    {
                        if (!File.Exists(TocFileLocation.Replace(".toc", ".dat")))
                            Utilities.Log("Can't Find DAT File.", Utilities.Event.Error, true, 1);
                        var datReader =
                            new BinaryReader(File.Open(TocFileLocation.Replace(".toc", ".dat"), FileMode.Open));
                        reader.ReadLine();

                        while (!reader.EndOfStream)
                        {
                            var line = reader.ReadLine();
                            if (line == null) continue;

                            line = line.TrimStart(' ');
                            line = Regex.Replace(line, @"  +", " ", RegexOptions.Compiled);
                            var Data = new FileInformation(line.Split(new char[] { ' ' }, 3));

                            Utilities.Log(
                                $"Extracting File: {new FileInfo(Data.FileName).Name} ({Data.FileSize} Bytes)",
                                Utilities.Event.Information);

                            new FileInfo("YGO_DATA/" + Data.FileName).Directory?.Create();

                            var ExtraBytes = Utilities.HexToDec(Data.FileSize);
                            if (Utilities.HexToDec(Data.FileSize) % 4 != 0)
                                while (ExtraBytes % 4 != 0)
                                    ExtraBytes = ExtraBytes + 1;

                            using (var FileWriter = new BinaryWriter(File.Open("YGO_DATA/" + Data.FileName,
                                FileMode.Create, FileAccess.Write)))
                            {
                                FileWriter.Write(datReader.ReadBytes(Utilities.HexToDec(Data.FileSize)));
                                FileWriter.Flush();
                            }

                            datReader.BaseStream.Position += ExtraBytes - Utilities.HexToDec(Data.FileSize);
                        }
                    }
                }
                catch (Exception Ex)
                {
                    Utilities.Log($"Exception Caught: {Ex.Message}", Utilities.Event.Error, true, 1);
                }
            }
        }

19 Source : ContextMenuFunctions.cs
with MIT License
from Arefu

public static void ExtractFile(ListViewItem Item, string ExportPath = "")
        {
            var FileToExport = Form1.Data.First(File => File.Item3.Contains(Item.Text));

            var BytesToRead = 0L;
            foreach (var File in Form1.Data)
            {
                if (File.Item3 == FileToExport.Item3)
                    break;

                while (File.Item1 % 4 != 0)
                    File.Item1 = File.Item1 + 1;

                BytesToRead = File.Item1 + BytesToRead;

                if (File.Item3 == FileToExport.Item3)
                    break;
            }

            using (var BReader =
                new BinaryReader(File.Open($"{Form1.InstallDir}\\YGO_DATA.dat", FileMode.Open, FileAccess.Read)))
            {
                if (ExportPath == "")
                    ExportPath = $"Exported/{FileToExport.Item3}";

                new FileInfo(ExportPath).Directory?.Create();
                using (var Writer = new BinaryWriter(File.Open(ExportPath, FileMode.OpenOrCreate, FileAccess.Write)))
                {
                    BReader.BaseStream.Position = BytesToRead;
                    Writer.Write(BReader.ReadBytes(FileToExport.Item1));
                }
            }
        }

19 Source : ImageRepository.cs
with MIT License
from Arefu

private void CreatePathIfNotExists(DirectoryInfo path)
        {
            if (!path.Exists)
            {
                path.Create();
            }
        }

19 Source : AddonCompiler.cs
with GNU General Public License v3.0
from armandoalonso

private void CreateAddonFiles(C3Addon addon, string folderName)
        {
            //generate file strings
            _addonFiles = new Dictionary<string, string>();


            LogManager.CompilerLog.Insert($"generating addon.json");
            //generate addon json files
            _addonFiles.Add(Path.Combine(
                OptionsManager.CurrentOptions.CompilePath, folderName, "addon.json"), 
                LogManager.CompilerLog.WrapLogger(() => FormatHelper.Insatnce.Json(addon.AddonJson)));
            LogManager.CompilerLog.Insert($"generating addon.json => complete");

            if (addon.Type == PluginType.Behavior)
            {
                LogManager.CompilerLog.Insert($"generating behavior.js (edittime)");
                _addonFiles.Add(
                    Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "behavior.js"), 
                    ConsoleLogRemover.Insatnce.CommentOut(FormatHelper.Insatnce.Javascript(addon.PluginEditTime)));
                LogManager.CompilerLog.Insert($"generating behavior.js (edittime) => complete");

                LogManager.CompilerLog.Insert($"generating behavior.js (runtime)");
                _addonFiles.Add(
                    Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "c3runtime", "behavior.js"),
                    ConsoleLogRemover.Insatnce.CommentOut(FormatHelper.Insatnce.Javascript(addon.PluginRunTime)));
                LogManager.CompilerLog.Insert($"generating behavior.js (runtime) => complete");
            }
            else
            {
                LogManager.CompilerLog.Insert($"generating plugin.js (edittime)");
                _addonFiles.Add(
                    Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "plugin.js"),
                    ConsoleLogRemover.Insatnce.CommentOut(FormatHelper.Insatnce.Javascript(addon.PluginEditTime)));
                LogManager.CompilerLog.Insert($"generating plugin.js (edittime) => complete");

                LogManager.CompilerLog.Insert($"generating plugin.js (runtime)");
                _addonFiles.Add(
                    Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "c3runtime", "plugin.js"),
                    ConsoleLogRemover.Insatnce.CommentOut(FormatHelper.Insatnce.Javascript(addon.PluginRunTime)));
                LogManager.CompilerLog.Insert($"generating plugin.js (runtime) => complete");
            }

            LogManager.CompilerLog.Insert($"generating type.js (edittime)");
            _addonFiles.Add(
                Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "type.js"),
                ConsoleLogRemover.Insatnce.CommentOut(FormatHelper.Insatnce.Javascript(addon.TypeEditTime)));
            LogManager.CompilerLog.Insert($"generating type.js (edittime) => complete");

            LogManager.CompilerLog.Insert($"generating instance.js (edittime)");
            _addonFiles.Add(
                Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "instance.js"),
                ConsoleLogRemover.Insatnce.CommentOut(FormatHelper.Insatnce.Javascript(addon.InstanceEditTime)));
            LogManager.CompilerLog.Insert($"generating instance.js (edittime) => complete");

            LogManager.CompilerLog.Insert($"generating ace.json");
            _addonFiles.Add(Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "aces.json"), LogManager.CompilerLog.WrapLogger(() => FormatHelper.Insatnce.Json(CompileAce(addon))));
            LogManager.CompilerLog.Insert($"generating ace.json => complete");

            LogManager.CompilerLog.Insert($"generating en-US.json");
            _addonFiles.Add(Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "lang", "en-US.json"), LogManager.CompilerLog.WrapLogger(() => FormatHelper.Insatnce.Json(CompileLang(addon))));
            LogManager.CompilerLog.Insert($"generating en-US.json => complete");

            LogManager.CompilerLog.Insert($"generating type.js (runtime)");
            _addonFiles.Add(Path.Combine(
                OptionsManager.CurrentOptions.CompilePath, folderName, "c3runtime", "type.js"),
                ConsoleLogRemover.Insatnce.CommentOut(FormatHelper.Insatnce.Javascript(addon.TypeRunTime)));
            LogManager.CompilerLog.Insert($"generating type.js (runtime) => complete");

            LogManager.CompilerLog.Insert($"generating instance.js (runtime)");
            _addonFiles.Add(
                Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "c3runtime", "instance.js"),
                ConsoleLogRemover.Insatnce.CommentOut(FormatHelper.Insatnce.Javascript(addon.InstanceRunTime)));
            LogManager.CompilerLog.Insert($"generating instance.js (runtime) => complete");

            LogManager.CompilerLog.Insert($"generating action.js");
            _addonFiles.Add(
                Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "c3runtime", "actions.js"),
                ConsoleLogRemover.Insatnce.CommentOut(FormatHelper.Insatnce.Javascript(CompileActions(addon))));
            LogManager.CompilerLog.Insert($"generating action.js => complete");

            LogManager.CompilerLog.Insert($"generating conditions.js");
            _addonFiles.Add(
                Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "c3runtime", "conditions.js"),
                ConsoleLogRemover.Insatnce.CommentOut(FormatHelper.Insatnce.Javascript(CompileConditions(addon))));
            LogManager.CompilerLog.Insert($"generating conditions.js => complete");

            LogManager.CompilerLog.Insert($"generating expressions.js");
            _addonFiles.Add(Path.Combine(
                OptionsManager.CurrentOptions.CompilePath, folderName, "c3runtime", "expressions.js"),
                ConsoleLogRemover.Insatnce.CommentOut(FormatHelper.Insatnce.Javascript(CompileExpressions(addon))));
            LogManager.CompilerLog.Insert($"generating expressions.js => complete");

            LogManager.CompilerLog.Insert("generating 3rd party files");
            foreach (var files in addon.ThirdPartyFiles.Values)
            {
                string content = string.Empty;
                if (files.PlainText)
                {
                    if (files.Compress)
                    {
                        content = FormatHelper.Insatnce.CompressMinifiedFiles(files.Content);
                    }
                    else
                    {
                        content = files.Content;
                    }
                    if (files.Rootfolder) _addonFiles.Add(Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, files.FileName), content);
                    if (files.C3Folder) _addonFiles.Add(Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "c3runtime", files.FileName), content);
                    if (files.C2Folder) _addonFiles.Add(Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "c2runtime", files.FileName), content);
                }
                else
                {
                    if (files.Rootfolder) File.WriteAllBytes(Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, files.FileName), files.Bytes);
                    if (files.C3Folder) File.WriteAllBytes(Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "c3runtime", files.FileName), files.Bytes);
                    if (files.C2Folder) File.WriteAllBytes(Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "c2runtime", files.FileName), files.Bytes);
                }

                LogManager.CompilerLog.Insert($"generating {files.FileName}");
            }
            LogManager.CompilerLog.Insert("generating 3rd party files => complete");

            if (!string.IsNullOrWhiteSpace(addon.C2RunTime))
            {
                LogManager.CompilerLog.Insert("generating c2runtime file");
                _addonFiles.Add(
                    Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "c2runtime", "runtime.js"),
                    ConsoleLogRemover.Insatnce.CommentOut(FormatHelper.Insatnce.Javascript(addon.C2RunTime)));
                LogManager.CompilerLog.Insert("generating c2runtime file => complete");
            }

            //write files to path
            foreach (var file in _addonFiles)
            {
                var fi = new FileInfo(file.Key);
                if(fi.Directory != null && !fi.Directory.Exists) fi.Directory.Create(); 
                System.IO.File.WriteAllText(file.Key, file.Value);
                LogManager.CompilerLog.Insert($"writing file => {file.Key}");
            }

            File.WriteAllText(Path.Combine(OptionsManager.CurrentOptions.CompilePath, folderName, "icon.svg"), addon.IconXml);
            LogManager.CompilerLog.Insert($"writing file => icon.svg");
            LogManager.CompilerLog.Insert($"compilation complete...");
        }

19 Source : Factorio.cs
with GNU General Public License v3.0
from Artentus

public static async Task<(bool, IFactorioInstance?)> TryExtract(FileInfo archiveFile, string destination, string? dirName = null)
        {
            var destinationDir = new DirectoryInfo(destination);
            if (!destinationDir.Exists) destinationDir.Create();

            var (valid, extractName) = await Task.Run(() =>
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    return ExtractWin32(archiveFile, destination);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    return ExtractLinux(archiveFile, destination);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    return ExtractMac(archiveFile, destination);
                }
                else
                {
                    throw new PlatformNotSupportedException();
                }
            });

            if (!valid)
            {
                if (!string.IsNullOrEmpty(extractName))
                {
                    // We may have extracted some files already, but they must
                    // all reside in a directory called 'Factorio_*' so we can
                    // clean up easily.
                    var dir = destinationDir.EnumerateDirectories(extractName).FirstOrDefault();
                    if (!(dir is null)) dir.Delete(true);
                }

                return (false, null);
            }
            else
            {
                var dir = destinationDir.EnumerateDirectories(extractName).First(); // Must exist
                if (!string.IsNullOrEmpty(dirName))
                    dir.MoveTo(Path.Combine(dir.Parent.FullName, dirName));

                var (success, instance) = await TryLoadAsync(dir);
                if (!success) dir.Delete();
                return (success, instance);
            }
        }

19 Source : DirectoryInfoExtensions.cs
with GNU General Public License v3.0
from Artentus

public static async Task<DirectoryInfo> CopyToAsync(this DirectoryInfo directory, string path)
        {
            var newDir = new DirectoryInfo(path);
            if (!newDir.Exists) newDir.Create();

            foreach (var file in directory.EnumerateFiles())
                await file.CopyToAsync(Path.Combine(newDir.FullName, file.Name));

            foreach (var subDir in directory.EnumerateDirectories())
                await CopyToAsync(subDir, Path.Combine(newDir.FullName, subDir.Name));

            return newDir;
        }

19 Source : DirectoryInfoExtensions.cs
with GNU General Public License v3.0
from Artentus

public static async Task<DirectoryInfo> MoveToAsync(this DirectoryInfo directory, string path)
        {
            var root1 = Path.GetPathRoot(directory.FullName);
            var root2 = Path.GetPathRoot(path);
            if (string.Equals(root1, root2, StringComparison.OrdinalIgnoreCase)) // Functionality integrated
            {
                directory.MoveTo(path);
                return directory;
            }
            else // Moving all files one-by-one
            {
                var newDir = new DirectoryInfo(path);
                if (!newDir.Exists) newDir.Create();

                foreach (var file in directory.EnumerateFiles())
                    await file.MoveToAsync(Path.Combine(newDir.FullName, file.Name));

                foreach (var subDir in directory.EnumerateDirectories())
                    await MoveToAsync(subDir, Path.Combine(newDir.FullName, subDir.Name));

                directory.Delete();
                return newDir;
            }
        }

19 Source : FileInfoExtensions.cs
with GNU General Public License v3.0
from Artentus

public static async Task<FileInfo> CopyToAsync(this FileInfo file, string path)
        {
            var newFile = new FileInfo(path);
            if (!newFile.Directory.Exists) newFile.Directory.Create();

            using (var source = file.OpenRead())
            {
                using (var destination = newFile.Open(FileMode.CreateNew, FileAccess.Write))
                    await source.CopyToAsync(destination);
            }

            return newFile;
        }

19 Source : FileInfoExtensions.cs
with GNU General Public License v3.0
from Artentus

public static async Task<FileInfo> MoveToAsync(this FileInfo file, string path)
        {
            var root1 = Path.GetPathRoot(file.FullName);
            var root2 = Path.GetPathRoot(path);
            if (string.Equals(root1, root2, StringComparison.OrdinalIgnoreCase)) // Moving to same drive is almost instant
            {
                var newFile = new FileInfo(path);
                if (!newFile.Directory.Exists) newFile.Directory.Create();

                file.MoveTo(newFile.FullName);
                return newFile;
            }
            else // Moving to different drive is a copy then delete
            {
                var newFile = await CopyToAsync(file, path);
                file.Delete();
                return newFile;
            }
        }

19 Source : ExtractedModFile.cs
with GNU General Public License v3.0
from Artentus

public async Task<ZippedModFile> PackAsync(string destination)
        {
            bool wasEnabled = Enabled;
            if (!wasEnabled) Enabled = true;

            var newFile = new FileInfo(Path.Combine(destination, _directory.Name + ".zip"));
            if (!newFile.Directory.Exists) newFile.Directory.Create();

            await Task.Run(() =>
            {
                using var fs = newFile.Open(FileMode.Create, FileAccess.Write);
                using var writer = new ZipWriter(fs, new ZipWriterOptions(CompressionType.Deflate));
                PopulateZipArchive(writer, _directory, _directory.Name);
            });

            var newThumbnail = await ModFile.CopyThumbnailAsync(Thumbnail);
            var zippedFile = new ZippedModFile(newFile, Info, newThumbnail);

            if (!wasEnabled)
            {
                zippedFile.Enabled = false;
                Enabled = false;
            }
            return zippedFile;
        }

19 Source : ModFamilyStateGrouping.cs
with GNU General Public License v3.0
from Artentus

public async Task SaveToFileAsync(FileInfo file, Formatting formatting = Formatting.Indented, JsonSerializerSettings? settings = null)
        {
            if (!file.Directory.Exists) file.Directory.Create();

            using var stream = new FileStream(file.FullName, FileMode.Create, FileAccess.Write, FileShare.None,
                                              4096, FileOptions.Asynchronous | FileOptions.SequentialScan);

            string json = ToJson(formatting, settings);
            var buffer = Encoding.UTF8.GetBytes(json);

            await stream.WriteAsync(buffer, 0, buffer.Length);
        }

19 Source : ModInfo.cs
with GNU General Public License v3.0
from Artentus

public async Task SaveToFileAsync(FileInfo file, Formatting formatting = Formatting.Indented, JsonSerializerSettings? settings = null)
        {
            if (!file.Directory.Exists) file.Directory.Create();
            using var fs = file.Open(FileMode.Create, FileAccess.Write);
            using var writer = new StreamWriter(fs);
            string json = ToJson(formatting, settings);
            await writer.WriteAsync(json);
        }

19 Source : Exporter.cs
with GNU General Public License v3.0
from Artentus

private void ExportArchive(FileInfo file, Formatting formatting, JsonSerializerSettings? settings)
        {
            if (!file.Directory.Exists) file.Directory.Create();

            using var stream = file.Open(FileMode.Create, FileAccess.Write);
            // We can choose best speed here because the only thing we're compressing is other zip archives and some JSON
            var options = new ZipWriterOptions(CompressionType.Deflate) { DeflateCompressionLevel = CompressionLevel.BestSpeed };
            using var writer = new ZipWriter(stream, options);

            string json = JsonConvert.SerializeObject(Package, formatting, settings);
            byte[] data = Encoding.UTF8.GetBytes(json);
            using var jsonStream = new MemoryStream(data);
            writer.Write("pack.json", jsonStream);

            foreach (var f in FilesToPack)
                writer.Write(f.Name, f);
        }

19 Source : Importer.cs
with GNU General Public License v3.0
from Artentus

private static ImportResult ImportArchive(FileInfo file, string tempPath)
        {
            var tempDir = new DirectoryInfo(tempPath);
            if (!tempDir.Exists) tempDir.Create();

            Package? package = null;
            var extractedFiles = new List<FileInfo>();

            using var stream = file.OpenRead();
            using var reader = ZipReader.Open(stream);
            while (reader.MoveToNextEntry())
            {
                if (string.Equals(reader.Entry.Key, "pack.json", StringComparison.OrdinalIgnoreCase))
                {
                    using var jsonStream = new MemoryStream((int)reader.Entry.Size);
                    reader.WriteEntryTo(jsonStream);
                    jsonStream.Position = 0;

                    using var jsonReader = new StreamReader(jsonStream);
                    string json = jsonReader.ReadToEnd();
                    package = JsonConvert.DeserializeObject<Package>(json);
                }
                else
                {
                    string path = Path.Combine(tempPath, reader.Entry.Key);
                    var extFile = new FileInfo(path);
                    reader.WriteEntryTo(extFile);
                    extractedFiles.Add(extFile);
                }
            }

            if (package is null) throw new ImportException("File did not contain a valid package description");
            return new ImportResult(package, extractedFiles);
        }

See More Examples