System.IO.Directory.CreateDirectory(string)

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

9644 Examples 7

19 Source : CelesteNetEmojiComponent.cs
with MIT License
from 0x0ade

public void Handle(CelesteNetConnection con, DataNetEmoji netemoji) {
            Logger.Log(LogLevel.VVV, "netemoji", $"Received {netemoji.ID}");

            string dir = Path.Combine(Path.GetTempPath(), "CelesteNetClientEmojiCache");
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            string path = Path.Combine(dir, $"{netemoji.ID}-{netemoji.GetHashCode():X8}.png");
            using (FileStream fs = File.OpenWrite(path))
            using (MemoryStream ms = new(netemoji.Data))
                ms.CopyTo(fs);

            RunOnMainThread(() => {
                Logger.Log(LogLevel.VVV, "netemoji", $"Registering {netemoji.ID}");

                bool registered = false;

                try {
                    VirtualTexture vt = VirtualContent.CreateTexture(path);
                    MTexture mt = new(vt);
                    if (vt.Texture_Safe == null) // Needed to trigger lazy loading.
                        throw new Exception($"Couldn't load emoji {netemoji.ID}");

                    Registered.Add(netemoji.ID);
                    RegisteredFiles.Add(path);
                    Emoji.Register(netemoji.ID, mt);
                    Emoji.Fill(CelesteNetClientFont.Font);
                    registered = true;

                } finally {
                    if (!registered)
                        File.Delete(path);
                }
            });
        }

19 Source : patch_DuckFile.cs
with MIT License
from 0x0ade

public static void Initialize() {
            orig_Initialize();
            string prefix = _saveRoot + _saveDirectory;
            foreach (string path in _allPaths) {
                if (path.StartsWith(prefix))
                    Directory.CreateDirectory(path);
                else
                    Directory.CreateDirectory(prefix + path);
            }
        }

19 Source : XnaToFnaUtil.cs
with zlib License
from 0x0ade

public void RestoreBackup(string root, string origRoot) {
            Log($"[RestoreBackup] Restoring from {origRoot} to {root}");
            foreach (string origPath in Directory.EnumerateFiles(origRoot, "*", SearchOption.AllDirectories)) {
                Directory.CreateDirectory(Path.GetDirectoryName(root + origPath.Substring(origRoot.Length)));
                File.Copy(origPath, root + origPath.Substring(origRoot.Length), true);
            }
        }

19 Source : Program.cs
with MIT License
from 0x1000000

private static string EnsureDirectory(string directory, ILogger logger, string dirAlias, bool create)
        {
            if (string.IsNullOrEmpty(directory))
            {
                directory = Directory.GetCurrentDirectory();
                logger.LogDetailed(
                    $"{dirAlias} directory was not specified, so the current directory \"{directory}\" is used as an output one.");
            }
            else if (!Path.IsPathFullyQualified(directory))
            {
                directory = Path.GetFullPath(directory, Directory.GetCurrentDirectory());
                logger.LogDetailed($"{dirAlias} directory is converted to fully qualified \"{directory}\".");
            }


            if (!Directory.Exists(directory))
            {
                if (create)
                {
                    try
                    {
                        Directory.CreateDirectory(directory);
                        logger.LogDetailed($"Directory \"{directory}\" was created.");
                    }
                    catch (Exception e)
                    {
                        throw new SqExpressCodeGenException($"Could not create directory: \"{directory}\".", e);
                    }
                }
                else
                {
                    throw new SqExpressCodeGenException($"\"{directory}\" directory does not exist.");
                }
            }

            return directory;
        }

19 Source : LocalStorageHandler.cs
with Apache License 2.0
from 0xFireball

private string GetUploadDirectory()
        {
            var uploadDirectory = Path.Combine(ServerContext.Configuration.UploadDirectory);

            Directory.CreateDirectory(uploadDirectory);

            return uploadDirectory;
        }

19 Source : IrdClient.cs
with MIT License
from 13xforever

public async Task<Ird> DownloadAsync(SearchResulreplacedem irdInfo, string localCachePath, CancellationToken cancellationToken)
        {
            Ird result = null;
            try
            {
                var localCacheFilename = Path.Combine(localCachePath, irdInfo.Filename);
                // first we search local cache and try to load whatever data we can
                try
                {
                    if (File.Exists(localCacheFilename))
                        return IrdParser.Parse(File.ReadAllBytes(localCacheFilename));
                }
                catch (Exception e)
                {
                    Log.Warn(e, "Error accessing local IRD cache: " + e.Message);
                }
                try
                {
                    var resultBytes = await client.GetByteArrayAsync(GetDownloadLink(irdInfo.Filename)).ConfigureAwait(false);
                    result = IrdParser.Parse(resultBytes);
                    try
                    {
                        if (!Directory.Exists(localCachePath))
                            Directory.CreateDirectory(localCachePath);
                        File.WriteAllBytes(localCacheFilename, resultBytes);
                    }
                    catch (Exception ex)
                    {
                        Log.Warn(ex, $"Failed to write {irdInfo.Filename} to local cache: {ex.Message}");
                    }
                }
                catch (Exception e)
                {
                    Log.Warn(e, $"Failed to download {irdInfo.Filename}: {e.Message}");
                }
                return result;
            }
            catch (Exception e)
            {
                Log.Error(e);
                return result;
            }
        }

19 Source : Dumper.cs
with MIT License
from 13xforever

public async Task DumpAsync(string output)
        {
            // check and create output folder
            var dumpPath = output;
            while (!string.IsNullOrEmpty(dumpPath) && !Directory.Exists(dumpPath))
            {
                var parent = Path.GetDirectoryName(dumpPath);
                if (parent == null || parent == dumpPath)
                    dumpPath = null;
                else
                    dumpPath = parent;
            }
            if (filesystemStructure is null)
                (filesystemStructure, emptyDirStructure) = GetFilesystemStructure();
            var validators = GetValidationInfo();
            if (!string.IsNullOrEmpty(dumpPath))
            {
                var root = Path.GetPathRoot(Path.GetFullPath(output));
                var drive = DriveInfo.GetDrives().FirstOrDefault(d => d?.RootDirectory.FullName.StartsWith(root) ?? false);
                if (drive != null)
                {
                    var spaceAvailable = drive.AvailableFreeSpace;
                    TotalFileSize = filesystemStructure.Sum(f => f.Length);
                    var diff = TotalFileSize + 100 * 1024 - spaceAvailable;
                    if (diff > 0)
                        Log.Warn($"Target drive might require {diff.replacedtorageUnit()} of additional free space");
                }
            }

            foreach (var dir in emptyDirStructure)
                Log.Trace($"Empty dir: {dir}");
            foreach (var file in filesystemStructure)
                Log.Trace($"0x{file.StartSector:x8}: {file.Filename} ({file.Length})");
            var outputPathBase = Path.Combine(output, OutputDir);
            if (!Directory.Exists(outputPathBase))
                Directory.CreateDirectory(outputPathBase);

            TotalFileCount = filesystemStructure.Count;
            TotalSectors = discReader.TotalClusters;
            Log.Debug("Using decryption key: " + allMatchingKeys.First().DecryptedKeyId);
            var decryptionKey = allMatchingKeys.First().DecryptedKey;
            var sectorSize = (int)discReader.ClusterSize;
            var unprotectedRegions = driveStream.GetUnprotectedRegions();
            ValidationStatus = true;

            foreach (var dir in emptyDirStructure)
            {
                try
                {
                    if (Cts.IsCancellationRequested)
                        return;

                    var convertedName = Path.DirectorySeparatorChar == '\\' ? dir : dir.Replace('\\', Path.DirectorySeparatorChar);
                    var outputName = Path.Combine(outputPathBase, convertedName);
                    if (!Directory.Exists(outputName))
                    {
                        Log.Debug("Creating empty directory " + outputName);
                        Directory.CreateDirectory(outputName);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    BrokenFiles.Add((dir, "Unexpected error: " + ex.Message));
                }
            }
            
            foreach (var file in filesystemStructure)
            {
                try
                {
                    if (Cts.IsCancellationRequested)
                        return;

                    Log.Info($"Reading {file.Filename} ({file.Length.replacedtorageUnit()})");
                    CurrentFileNumber++;
                    var convertedFilename = Path.DirectorySeparatorChar == '\\' ? file.Filename : file.Filename.Replace('\\', Path.DirectorySeparatorChar);
                    var inputFilename = Path.Combine(input, convertedFilename);

                    if (!File.Exists(inputFilename))
                    {
                        Log.Error($"Missing {file.Filename}");
                        BrokenFiles.Add((file.Filename, "missing"));
                        continue;
                    }

                    var outputFilename = Path.Combine(outputPathBase, convertedFilename);
                    var fileDir = Path.GetDirectoryName(outputFilename);
                    if (!Directory.Exists(fileDir))
                    {
                        Log.Debug("Creating directory " + fileDir);
                        Directory.CreateDirectory(fileDir);
                    }

                    var error = false;
                    var expectedHashes = (
                        from v in validators
                        where v.Files.ContainsKey(file.Filename)
                        select v.Files[file.Filename].Hashes
                    ).ToList();
                    var lastHash = "";
                    var tries = 2;
                    do
                    {
                        try
                        {
                            tries--;
                            using var outputStream = File.Open(outputFilename, FileMode.Create, FileAccess.Write, FileShare.Read);
                            using var inputStream = File.Open(inputFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
                            using var decrypter = new Decrypter(inputStream, driveStream, decryptionKey, file.StartSector, sectorSize, unprotectedRegions);
                            Decrypter = decrypter;
                            await decrypter.CopyToAsync(outputStream, 8 * 1024 * 1024, Cts.Token).ConfigureAwait(false);
                            outputStream.Flush();
                            var resultHashes = decrypter.GetHashes();
                            var resultMd5 = resultHashes["MD5"];
                            if (decrypter.WasEncrypted && decrypter.WasUnprotected)
                                Log.Debug("Partially decrypted " + file.Filename);
                            else if (decrypter.WasEncrypted)
                                Log.Debug("Decrypted " + file.Filename);

                            if (!expectedHashes.Any())
                            {
                                if (ValidationStatus == true)
                                    ValidationStatus = null;
                            }
                            else if (!IsMatch(resultHashes, expectedHashes))
                            {
                                error = true;
                                var msg = "Unexpected hash: " + resultMd5;
                                if (resultMd5 == lastHash || decrypter.LastBlockCorrupted)
                                {
                                    Log.Error(msg);
                                    BrokenFiles.Add((file.Filename, "corrupted"));
                                    break;
                                }
                                Log.Warn(msg + ", retrying");
                            }

                            lastHash = resultMd5;
                        }
                        catch (Exception e)
                        {
                            Log.Error(e, e.Message);
                            error = true;
                        }
                    } while (error && tries > 0 && !Cts.IsCancellationRequested);
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    BrokenFiles.Add((file.Filename, "Unexpected error: " + ex.Message));
                }
            }
            Log.Info("Completed");
        }

19 Source : ApplicationBuilderExtensions.cs
with MIT License
from 17MKH

public static IApplicationBuilder UseDefaultPage(this IApplicationBuilder app)
    {
        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/app");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        //设置默认文档
        var defaultFilesOptions = new DefaultFilesOptions();
        defaultFilesOptions.DefaultFileNames.Clear();
        defaultFilesOptions.DefaultFileNames.Add("index.html");
        app.UseDefaultFiles(defaultFilesOptions);

        var options = new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(path),
            RequestPath = new PathString("/app")
        };

        app.UseStaticFiles(options);

        var appPath = "app";
        var rewriteOptions = new RewriteOptions().AddRedirect("^$", appPath);

        app.UseRewriter(rewriteOptions);

        return app;
    }

19 Source : ServiceCollectionExtensions.cs
with MIT License
from 17MKH

public static IServiceCollection AddData(this IServiceCollection services, IModuleCollection modules)
    {
        foreach (var module in modules)
        {
            var dbOptions = module.Options!.Db;
            var dbContextType = module.Layerreplacedemblies.Core.GetTypes().FirstOrDefault(m => typeof(DbContext).IsreplacedignableFrom(m));

            var dbBuilder = services.AddMkhDb(dbContextType, opt =>
            {
                opt.Provider = dbOptions.Provider;

                //Sqlite数据库自动创建数据库文件
                if (dbOptions.ConnectionString.IsNull() && dbOptions.Provider == DbProvider.Sqlite)
                {
                    string dbFilePath = Path.Combine(AppContext.BaseDirectory, "db");
                    if (!Directory.Exists(dbFilePath))
                    {
                        Directory.CreateDirectory(dbFilePath);
                    }

                    dbOptions.ConnectionString = $"Data Source={dbFilePath}/{module.Code}.db;Mode=ReadWriteCreate";
                }

                opt.ConnectionString = dbOptions.ConnectionString;
                opt.Log = dbOptions.Log;
                opt.TableNamePrefix = dbOptions.TableNamePrefix;
                opt.TableNameSeparator = dbOptions.TableNameSeparator;
                opt.Version = dbOptions.Version;
            });

            //加载仓储
            dbBuilder.AddRepositoriesFromreplacedembly(module.Layerreplacedemblies.Core);

            //启用代码优先
            if (dbOptions.CodeFirst)
            {
                dbBuilder.AddCodeFirst(opt =>
                {
                    opt.CreateDatabase = dbOptions.CreateDatabase;
                    opt.UpdateColumn = dbOptions.UpdateColumn;
                    opt.InitData = dbOptions.InitData;
                    opt.InitDataFilePath = module.DbInitFilePath;
                });
            }

            //特性事务
            foreach (var dic in module.ApplicationServices)
            {
                dbBuilder.AddTransactionAttribute(dic.Key, dic.Value);
            }

            dbBuilder.Build();
        }

        return services;
    }

19 Source : GeneratorOptionsSerializer.cs
with MIT License
from 188867052

public string Save(string directory)
        {
            if (string.IsNullOrWhiteSpace(directory))
            {
                directory = Environment.CurrentDirectory;
            }

            if (!Directory.Exists(directory))
            {
                this.logger.LogTrace($"Creating Directory: {directory}");
                Directory.CreateDirectory(directory);
            }

            return string.Empty;
        }

19 Source : FauxDeployCMAgent.cs
with GNU General Public License v3.0
from 1RedOne

public static void SendCustomDiscovery(string CMServerName, string ClientName, string SiteCode, string FilePath, ObservableCollection<CustomClientRecord> customClientRecords)
        {
            string ddmLocal = FilePath + "\\DDRS\\" + ClientName;
            string CMddmInbox = "\\\\" + CMServerName + "\\SMS_" + SiteCode + "\\inboxes\\ddm.box\\" + ClientName + ".DDR";

            DiscoveryDataRecordFile ddrF = new DiscoveryDataRecordFile("ClientFaux")
            {
                SiteCode = SiteCode,
                Architecture = "System"
            };
            ddrF.AddStringProperty("Name", DdmDiscoveryFlags.Key, 32, ClientName);
            ddrF.AddStringProperty("Netbios Name", DdmDiscoveryFlags.Name, 16, ClientName);

            foreach (CustomClientRecord Record in customClientRecords)
            {
                ddrF.AddStringProperty(Record.RecordName, DdmDiscoveryFlags.None, 32, Record.RecordValue);
            }

            System.IO.Directory.CreateDirectory(ddmLocal);
            DirectoryInfo di = new DirectoryInfo(ddmLocal);
            ddrF.SerializeToFile(ddmLocal);

            FileInfo file = di.GetFiles().FirstOrDefault();

            File.Copy(file.FullName, CMddmInbox, true);
            System.IO.Directory.Delete(ddmLocal, true);
        }

19 Source : Form2.cs
with MIT License
from 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 Source : Utils.cs
with Apache License 2.0
from 214175590

public static void CopyDir(string fromDir, string toDir)
        {
            if (!Directory.Exists(fromDir))
                return;

            if (!Directory.Exists(toDir))
            {
                Directory.CreateDirectory(toDir);
            }

            string[] files = Directory.GetFiles(fromDir);
            foreach (string formFileName in files)
            {
                string fileName = Path.GetFileName(formFileName);
                string toFileName = Path.Combine(toDir, fileName);
                File.Copy(formFileName, toFileName);
            }
            string[] fromDirs = Directory.GetDirectories(fromDir);
            foreach (string fromDirName in fromDirs)
            {
                string dirName = Path.GetFileName(fromDirName);
                string toDirName = Path.Combine(toDir, dirName);
                CopyDir(fromDirName, toDirName);
            }
        }

19 Source : Form1.cs
with MIT License
from 200Tigersbloxed

private void Form1_Load(object sender, EventArgs e)
        {
            // check for internet
            if (CheckForInternetConnection() == true) { }
            else
            {
                MessageBox.Show("An Internet Connection is required!", "Not Connected to Internet", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
            // check if user can access website
            if (CheckForWebsiteConnection() == true) { }
            else
            {
                MessageBox.Show("Failed to connect to https://tigersserver.xyz. Please try again soon.", "Failed to Connect", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }

            WebClient client = new WebClient();
            Stream stream = client.OpenRead("https://pastebin.com/raw/S8v9a7Ba");
            StreamReader reader = new StreamReader(stream);
            String content = reader.ReadToEnd();
            if(version != content)
            {
                DialogResult drUpdate = MessageBox.Show("BSMulti-Installer is not up to date! Would you like to download the newest version?", "Uh Oh!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if(drUpdate == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start("https://github.com/200Tigersbloxed/BSMulti-Installer/releases/latest");
                    Application.Exit();
                }
            }

            checkForMessage();
            
            Directory.CreateDirectory("Files");
        }

19 Source : Form1.cs
with MIT License
from 200Tigersbloxed

void runVerifyCheck()
        {
            if (verifyPermissions(bsl)) { }
            else
            {
                MessageBox.Show("Please run the installer as administrator to continue! (Beat Saber Folder Denied)", "Access Denied to Folder", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
            if(Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + @"\Files"))
            {
                if (verifyPermissions(AppDomain.CurrentDomain.BaseDirectory + @"\Files")) { }
                else
                {
                    MessageBox.Show("Please run the installer as administrator to continue! (Installer Folder Denied)", "Access Denied to Folder", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Application.Exit();
                }
            }
            else
            {
                Directory.CreateDirectory("Files");
                if (verifyPermissions(AppDomain.CurrentDomain.BaseDirectory + @"\Files")) { }
                else
                {
                    MessageBox.Show("Please run the installer as administrator to continue! (Installer Folder Denied)", "Access Denied to Folder", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Application.Exit();
                }
            }
        }

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

private void CentralServerConfigForm_Load(object sender, EventArgs e)
        {
            if(monitorForm != null){
                this.Text = "Docker公共配置 - " + monitorForm.getSessionConfig().Host;
                cfgDir = MainForm.TEMP_DIR + monitorForm.getSessionConfig().Host;
                cfgDir = cfgDir.Replace("\\", "/");
                if (!Directory.Exists(cfgDir))
                {
                    Directory.CreateDirectory(cfgDir);
                }

                string cfgPath = monitorForm.getSessionConfig().CentralServerConfigDir;
                if (string.IsNullOrWhiteSpace(cfgPath))
                {
                    string home = monitorForm.getSftp().getHome();
                    if (!home.EndsWith("/"))
                    {
                        home += "/";
                    }
                    remoteCfgPath = home + "docker/central-server-config";
                    monitorForm.getSessionConfig().CentralServerConfigDir = remoteCfgPath;
                    AppConfig.Instance.SaveConfig(2);
                }
                else
                {
                    remoteCfgPath = cfgPath;
                }                

                stb_remote_dir.Text = remoteCfgPath;

                LoadRemoteYmls();
            }
            else
            {
                btn_reload.Enabled = false;
                btn_show.Enabled = false;
                下载到本地ToolStripMenuItem.Enabled = false;
                上传到服务器ToolStripMenuItem.Enabled = false;
                更改文件名ToolStripMenuItem.Enabled = false;
                删除文件ToolStripMenuItem.Enabled = false;
                this.AllowDrop = true;
            }
        }

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

public void init()
        {
            // 创建目录
            if (!Directory.Exists(SESSION_DIR))
            {
                Directory.CreateDirectory(SESSION_DIR);
            }
            if (!Directory.Exists(CONF_DIR))
            {
                Directory.CreateDirectory(CONF_DIR);
            }
            if (!Directory.Exists(HELP_DIR))
            {
                Directory.CreateDirectory(HELP_DIR);
            }
            if (!Directory.Exists(TEMP_DIR))
            {
                Directory.CreateDirectory(TEMP_DIR);
            }            

            // 渲染Session列表
            RenderSessionList();

        }

19 Source : TemplateGenerator.cs
with MIT License
from 2881099

public void Build(IDbFirst dbfirst, string templateDirectory, string outputDirectory, params string[] database) {
			if (dbfirst == null) throw new ArgumentException("dbfirst 参数不能为 null");
			if (string.IsNullOrEmpty(templateDirectory) || Directory.Exists(templateDirectory) == false) throw new ArgumentException("templateDirectory 目录不存在");
			if (string.IsNullOrEmpty(templateDirectory)) throw new ArgumentException("outputDirectory 不能为 null");
			if (database == null || database.Any() == false) throw new ArgumentException("database 参数不能为空");
			if (Directory.Exists(outputDirectory) == false) Directory.CreateDirectory(outputDirectory);
			templateDirectory = new DirectoryInfo(templateDirectory).FullName;
			outputDirectory = new DirectoryInfo(outputDirectory).FullName;
			if (templateDirectory.IndexOf(outputDirectory, StringComparison.CurrentCultureIgnoreCase) != -1) throw new ArgumentException("outputDirectory 目录不能设置在 templateDirectory 目录内");
			var tables = dbfirst.GetTablesByDatabase(database);
			var tpl = new TemplateEngin(templateDirectory, "FreeSql", "FreeSql.DatabaseModel");
			BuildEachDirectory(templateDirectory, outputDirectory, tpl, dbfirst, tables);
			tpl.Dispose();
		}

19 Source : CodeGenerate.cs
with MIT License
from 2881099

public async Task<string> Setup(Models.TaskBuild task)
        {



            try
            {
                var paths = await Task.Run(() =>
                 {

                     var config = new TemplateServiceConfiguration();
                     config.EncodedStringFactory = new RawStringFactory();
                     var service = RazorEngineService.Create(config);
                     Engine.Razor = service;


                     ///本次要操作的数据库
                     var dataBases = task.TaskBuildInfos.Where(a => a.Level == 1).ToList();

                     string path = string.Empty;

                     foreach (var db in dataBases)
                     {
                         //创建数据库连接
                         using (IFreeSql fsql = new FreeSql.FreeSqlBuilder()
                        .UseConnectionString(db.DataBaseConfig.DataType, db.DataBaseConfig.ConnectionStrings)
                        .Build())
                         {

                             //取指定数据库信息
                             var tables = fsql.DbFirst.GetTablesByDatabase(db.Name);
							 var outputTables = tables;

                             //是否有指定表
                             var uTables = task.TaskBuildInfos.Where(a => a.Level > 1).Select(a => a.Name).ToArray();
                             if (uTables.Length > 0)
                                 //过滤不要的表
                                 outputTables = outputTables.Where(a => uTables.Contains(a.Name)).ToList();

                             //根据用户设置组装生成路径并验证目录是否存在
                             path = $"{task.GeneratePath}\\{db.Name}";
                             if (!Directory.Exists(path))
                                 Directory.CreateDirectory(path);

							 var razorId = Guid.NewGuid().ToString("N");
							 Engine.Razor.Compile(task.Templates.Code, razorId);
                             //开始生成操作
                             foreach (var table in outputTables)
                             {
								 var sw = new StringWriter();
								 var model = new RazorModel(fsql, task, tables, table);
								 Engine.Razor.Run(razorId, sw, null, model);
 

                                 StringBuilder plus = new StringBuilder();
                                 plus.AppendLine("//------------------------------------------------------------------------------");
                                 plus.AppendLine("// <auto-generated>");
                                 plus.AppendLine("//     此代码由工具生成。");
                                 plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                                 plus.AppendLine("//     Website: http://www.freesql.net");
                                 plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                                 plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                                 plus.AppendLine("// </auto-generated>");
                                 plus.AppendLine("//------------------------------------------------------------------------------");

                                 plus.Append(sw.ToString());

                                 plus.AppendLine();
                                 File.WriteAllText($"{path}\\{task.FileName.Replace("{name}", model.GetCsName(table.Name))}", plus.ToString());
                             }
                         }
                     }
                     return path;
                 });

                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                return "生成时发生异常,请检查模版代码.";
            }


        }

19 Source : TemplateGenerator.cs
with MIT License
from 2881099

void BuildEachDirectory(string templateDirectory, string outputDirectory, TemplateEngin tpl, IDbFirst dbfirst, List<DbTableInfo> tables) {
			if (Directory.Exists(outputDirectory) == false) Directory.CreateDirectory(outputDirectory);
			var files = Directory.GetFiles(templateDirectory);
			foreach (var file in files) {
				var fi = new FileInfo(file);
				if (string.Compare(fi.Extension, ".FreeSql", true) == 0) {
					var outputExtension = "." + fi.Name.Split('.')[1];
					if (fi.Name.StartsWith("for-table.")) {
						foreach (var table in tables) {
							var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "table", table }, { "dbfirst", dbfirst } });
							if (result.EndsWith("return;")) continue;
							var outputName = table.Name + outputExtension;
							var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
							if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
							var outputStream = Encoding.UTF8.GetBytes(result);
							var fullname = outputDirectory + "/" + outputName;
							if (File.Exists(fullname)) File.Delete(fullname);
							using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
								outfs.Write(outputStream, 0, outputStream.Length);
								outfs.Close();
							}
						}
						continue;
					} else {
						var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "tables", tables }, { "dbfirst", dbfirst } });
						var outputName = fi.Name;
						var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
						if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
						var outputStream = Encoding.UTF8.GetBytes(result);
						var fullname = outputDirectory + "/" + outputName;
						if (File.Exists(fullname)) File.Delete(fullname);
						using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
							outfs.Write(outputStream, 0, outputStream.Length);
							outfs.Close();
						}
					}
				}
				File.Copy(file, outputDirectory + file.Replace(templateDirectory, ""), true);
			}
			var dirs = Directory.GetDirectories(templateDirectory);
			foreach(var dir in dirs) {
				BuildEachDirectory(dir, outputDirectory +  dir.Replace(templateDirectory, ""), tpl, dbfirst, tables);
			}
		}

19 Source : CodeGenerate.cs
with MIT License
from 2881099

public async Task<string> Setup(TaskBuild taskBuild, List<DbTableInfo> outputTables)
        {
            try
            {
                var paths = await Task.Run(() =>
                {
                    var config = new TemplateServiceConfiguration();
                    config.EncodedStringFactory = new RawStringFactory();
                    Engine.Razor = RazorEngineService.Create(config);

                    string path = string.Empty;


                    foreach (var templatesPath in taskBuild.Templates)
                    {
                        path = $"{taskBuild.GeneratePath}\\{taskBuild.DbName}\\{templatesPath.Replace(".tpl", "").Trim()}";
                        if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                        var razorId = Guid.NewGuid().ToString("N");
                        var html = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Templates", templatesPath));
                        Engine.Razor.Compile(html, razorId);
                        //开始生成操作
                        foreach (var table in outputTables)
                        {
                            var sw = new StringWriter();
                            var model = new RazorModel(taskBuild, outputTables, table);
                            Engine.Razor.Run(razorId, sw, null, model);
                            StringBuilder plus = new StringBuilder();
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.AppendLine("// <auto-generated>");
                            plus.AppendLine("//     此代码由工具生成。");
                            plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                            plus.AppendLine("//     Website: http://www.freesql.net");
                            plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                            plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                            plus.AppendLine("// </auto-generated>");
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.Append(sw.ToString());
                            plus.AppendLine();
                            var outPath = $"{path}\\{taskBuild.FileName.Replace("{name}", model.GetCsName(table.Name))}";
                            if (!string.IsNullOrEmpty(taskBuild.RemoveStr))
                                outPath = outPath.Replace(taskBuild.RemoveStr, "").Trim();
                            File.WriteAllText(outPath, plus.ToString());
                        }
                    }
                    return path;
                });
                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成时发生异常,请检查模版代码: {ex.Message}.");
                return $"生成时发生异常,请检查模版代码: {ex.Message}.";
            }
        }

19 Source : FrmRazorTemplates.cs
with MIT License
from 2881099

private void buttonX1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxX1.Text))
            {
                ToastNotification.ToastBackColor = Color.Red;
                ToastNotification.ToastForeColor = Color.White;
                ToastNotification.ToastFont = new Font("微软雅黑", 15);
                ToastNotification.Show(this, "模版名称不允许为空", null, 3000, eToastGlowColor.Red, eToastPosition.TopCenter);
                return;
            }
            string path = Path.Combine(Environment.CurrentDirectory, "Templates");
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            TemplatesName = textBoxX1.Text;
            TemplatesPath = Path.Combine(path, $"{textBoxX1.Text}.tpl");
            if (File.Exists(TemplatesPath))
            {
                ToastNotification.ToastBackColor = Color.Red;
                ToastNotification.ToastForeColor = Color.White;
                ToastNotification.ToastFont = new Font("微软雅黑", 15);
                ToastNotification.Show(this, "模版名称己存在", null, 3000, eToastGlowColor.Red, eToastPosition.TopCenter);
                return;
            }
            using (var sr = File.Create(TemplatesPath))
            {
                sr.Close();
                sr.Dispose();
            }
            this.Close();
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

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

public static string GetTempPath()
        {
            string _tempPath = Path.Combine(StartupPath(), "v2ray_win_temp");
            if (!Directory.Exists(_tempPath))
            {
                Directory.CreateDirectory(_tempPath);
            }
            return _tempPath;
        }

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

public static void SaveLog(string strreplacedle, Exception ex)
        {
            try
            {
                string path = Path.Combine(StartupPath(), "guiLogs");
                string FilePath = Path.Combine(path, DateTime.Now.ToString("yyyyMMdd") + ".txt");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if (!File.Exists(FilePath))
                {
                    FileStream FsCreate = new FileStream(FilePath, FileMode.Create);
                    FsCreate.Close();
                    FsCreate.Dispose();
                }
                FileStream FsWrite = new FileStream(FilePath, FileMode.Append, FileAccess.Write);
                StreamWriter SwWrite = new StreamWriter(FsWrite);

                string strContent = ex.ToString();

                SwWrite.WriteLine(string.Format("{0}{1}[{2}]{3}", "--------------------------------", strreplacedle, DateTime.Now.ToString("HH:mm:ss"), "--------------------------------"));
                SwWrite.Write(strContent);
                SwWrite.WriteLine(Environment.NewLine);
                SwWrite.WriteLine(" ");
                SwWrite.Flush();
                SwWrite.Close();
            }
            catch { }
        }

19 Source : DirectoryUtil.cs
with MIT License
from 404Lcc

public static DirectoryInfo CreateDirectory(string path)
        {
            if (Directory.Exists(path)) return null;
            return Directory.CreateDirectory(path);
        }

19 Source : ImageHelper.cs
with MIT License
from 499116344

public static string CreateImageFromBytes(string fileName, byte[] buffer)
        {
            var file = fileName;
            var image = BytesToImage(buffer);
            var format = image.RawFormat;
            if (format.Equals(ImageFormat.Jpeg))
            {
                file += ".jpeg";
            }
            else if (format.Equals(ImageFormat.Png))
            {
                file += ".png";
            }
            else if (format.Equals(ImageFormat.Bmp))
            {
                file += ".bmp";
            }
            else if (format.Equals(ImageFormat.Gif))
            {
                file += ".gif";
            }
            else if (format.Equals(ImageFormat.Icon))
            {
                file += ".icon";
            }

            var info = new FileInfo(file);
            Directory.CreateDirectory(info.Directory.FullName);
            File.WriteAllBytes(file, buffer);
            return file;
        }

19 Source : SyntaxTreeFixerEditor.cs
with MIT License
from 71

protected override void Initialize(CSharpCompilation oldCompilation, CancellationToken _)
        {
            OptimizationLevel compilationConfiguration = oldCompilation.Options.OptimizationLevel;

            if (compilationConfiguration == OptimizationLevel.Debug && !runInDebug)
                return;
            if (compilationConfiguration == OptimizationLevel.Release && !runInRelease)
                return;

            CSharpCompilation EditCompilation(CSharpCompilation compilation, CancellationToken cancellationToken)
            {
                int syntaxTreesLength  = compilation.SyntaxTrees.Length;
                string randomDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

                for (int i = 0; i < syntaxTreesLength; i++)
                {
                    SyntaxTree tree = compilation.SyntaxTrees[i];
                    SyntaxTree nextTree = tree;

                    string treePath = tree.FilePath;

                    SourceText source = null;

                    if (nextTree.Encoding == null)
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            using (StreamWriter writer = new StreamWriter(ms, Encoding.UTF8, 4096, leaveOpen: true))
                            {
                                nextTree.GetText(cancellationToken).Write(writer, cancellationToken);
                            }

                            ms.Position = 0;

                            using (StreamReader reader = new StreamReader(ms, Encoding.UTF8, false, 4096, leaveOpen: true))
                            {
                                source = SourceText.From(reader, (int)ms.Length, Encoding.UTF8);

                                nextTree = nextTree.WithChangedText(source);
                            }
                        }
                    }

                    if (treePath != null && oldCompilation.SyntaxTrees.FirstOrDefault(x => x.FilePath == treePath) == tree)
                    {
                        // The tree already exists as a file, and is the one the user has;
                        // we don't need to change anything.

                        if (source == null)
                            // No changes applied
                            continue;

                        goto Replace;
                    }

                    if (!Directory.Exists(randomDirectory))
                         Directory.CreateDirectory(randomDirectory);

                    // The tree does not exist or has been changed by an editor,
                    // we need to change its filepath, and write a new file.
                    string newPath = string.IsNullOrEmpty(treePath)
                        ? Path.Combine(randomDirectory, Path.GetRandomFileName() + ".cs")
                        : Path.Combine(randomDirectory, Path.GetFileName(treePath));

                    nextTree = nextTree.WithFilePath(newPath);

                    using (FileStream fs = File.Open(newPath, FileMode.Create, FileAccess.Write))
                    using (StreamWriter writer = new StreamWriter(fs, nextTree.Encoding, 4096))
                    {
                        if (source == null)
                            source = nextTree.GetText(cancellationToken);

                        source.Write(writer, cancellationToken);
                    }

                    Replace:
                    compilation = compilation.ReplaceSyntaxTree(tree, nextTree);
                }

                return compilation;
            }

            CompilationPipeline += EditCompilation;
        }

19 Source : SimpleJSON.cs
with MIT License
from 734843327

public void SaveToFile(string aFileName)
		{
			System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
			using(var F = System.IO.File.OpenWrite(aFileName))
			{
				SaveToStream(F);
			}
		}

19 Source : Utility.IO.cs
with MIT License
from 7Bytes-Studio

public static void ExistsOrCreateFolder(string path)
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }

19 Source : C4Directory.cs
with MIT License
from 8T4

private static void LoadResource(string resourcesPath, string resourceName)
        {
            try
            {
                var path = Path.Join(resourcesPath, $"{resourceName}.puml");

                if (File.Exists(path))
                {
                    return;
                }

                var stream = ResourceMethods.GetResource($"{resourceName}.puml");
                Directory.CreateDirectory(resourcesPath);
                File.WriteAllText(path, stream);
            }
            catch (Exception e)
            {
                throw new C4FileException("An exception occured while the package try loading the resource files", e);
            }
        }

19 Source : UserCenterController.cs
with Apache License 2.0
from 91270

[HttpPost]
        [Authorization]
        public IActionResult AvatarUpload([FromForm(Name = "file")] IFormFile file)
        {
            try
            {

                if (Convert.ToBoolean(AppSettings.Configuration["AppSettings:Demo"]))
                {
                    return toResponse(StatusCodeType.Error, "当前为演示模式 , 您无权修改任何数据");
                }

                var fileExtName = Path.GetExtension(file.FileName).ToLower();

                var fileName = DateTime.Now.Ticks.ToString() + fileExtName;

                string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".jpeg" };

                int MaxContentLength = 1024 * 1024 * 4;

                if (!AllowedFileExtensions.Contains(fileExtName))
                {
                    return toResponse(StatusCodeType.Error, "上传失败,未经允许上传类型");
                }


                if (file.Length > MaxContentLength)
                {
                    return toResponse(StatusCodeType.Error, "上传图片过大,不能超过 " + (MaxContentLength / 1024).ToString() + " MB");
                }

                var filePath = $"/{DateTime.Now:yyyyMMdd}/";

                var avatarDirectory = $"{AppSettings.Configuration["AvatarUpload:AvatarDirectory"]}{filePath}";

                if (!Directory.Exists(avatarDirectory))
                {
                    Directory.CreateDirectory(avatarDirectory);
                }

                using (var stream = new FileStream($"{avatarDirectory}{fileName}", FileMode.Create))
                {
                    file.CopyTo(stream);
                }

                var avatarUrl = $"{AppSettings.Configuration["AvatarUpload:AvatarUrl"]}{filePath}{fileName}";

                var userSession = _tokenManager.GetSessionInfo();

                #region 更新用户信息
                var response = _usersService.Update(m => m.UserID == userSession.UserID, m => new Sys_Users
                {
                    AvatarUrl = avatarUrl,
                    UpdateID = userSession.UserID,
                    UpdateName = userSession.UserName,
                    UpdateTime = DateTime.Now
                });
                #endregion

                #region 更新登录会话记录

                _tokenManager.RefreshSession(userSession.UserID);

                #endregion

                return toResponse(avatarUrl);
            }
            catch (Exception)
            {
                throw;
            }
        }

19 Source : Download.cs
with GNU General Public License v3.0
from 9vult

public bool StartDownloading()
        {
            Logger.Log("[DL] Starting Download for '" + manga.mangaDirectory.FullName + "\\" + chapterNumber + "'");
            string chapterDirectory = manga.mangaDirectory.FullName + "\\" + chapterNumber;
            Directory.CreateDirectory(chapterDirectory); // Create a directory for this chapter

            switch (type)
            {
                case DownloadType.MANGA:
                    string jsonUrl = "https://mangadex.org/api/chapter/" + chapterID;
                    string json;
                    using (var wc = new System.Net.WebClient())
                        json = wc.DownloadString(jsonUrl);

                    dynamic contents = JsonConvert.DeserializeObject(json);
                    string server = contents.server;
                    string hash = contents.hash;
                    foreach (string file in contents.page_array)
                    {
                        if (server == "/data/")
                        {
                            server = "https://mangadex.org/data/";
                        }
                        string imgUrl = server + hash + "/" + file;
                        string imgFile = chapterDirectory + "\\" + file;

                        if (File.Exists(imgFile))
                        {
                            long length = new FileInfo(imgFile).Length;
                            if (length <= 0)
                            {
                                File.Delete(imgFile);
                            }
                        }
                        try
                        {
                            DownloadAsync(new Uri(imgUrl), imgFile);
                        } catch (Exception ex)
                        {
                            Logger.Error("[DL] Failed to download '" + imgUrl + "' because '" + ex.Message + "'");
                        }
                    }
                    CheckStartNext();
                    return true;

                case DownloadType.HENTAI:
                    string imageUrl = string.Empty;
                    string extension;
                    int pageCount = 0;
                    imageUrl = NHGetImageUrl(url);
                    pageCount = NHGetPageCount(url);
                    extension = NHGetImageExtension(imageUrl);
                    string imgLoc = NHGetImageLocation(imageUrl);

                    for (int page = 1; page <= pageCount; page++)
                    {
                        dlCount++;
                        string curImgUrl = imgLoc + page + "." + extension;
                        string imgFile = chapterDirectory + "\\" + page + "." + extension;
                        if (File.Exists(imgFile))
                        {
                            long length = new FileInfo(imgFile).Length;
                            if (length <= 0)
                            {
                                File.Delete(imgFile);
                                DownloadAsync(new Uri(curImgUrl), imgFile);
                            }
                            else
                            {
                                if (page == pageCount) // last one
                                    CheckStartNext();
                            }
                        }
                        else
                            DownloadAsync(new Uri(curImgUrl), imgFile);
                    }
                    return true;
                default:
                    return false;
            }
        }

19 Source : FrmStartPage.cs
with GNU General Public License v3.0
from 9vult

public void AddManga(string api, string num, bool isUpdate)
        {
            string json;
            if (api != null)
            {
                using (var wc = new System.Net.WebClient())
                {
                    json = wc.DownloadString(api);
                }
            }
            else
            {
                json = File.ReadAllText(homeFolder + "\\" + num + "\\manga.json");
            }

            // Deserialize the JSON file
            dynamic contents = JsonConvert.DeserializeObject(json);
            string mangaName = contents.manga.replacedle;
            string mangaDirectory = homeFolder + "\\" + num;

            if (!Directory.Exists(mangaDirectory))
            {
                Logger.Log("Creating directory '" + mangaDirectory + "' and related files");
                Directory.CreateDirectory(mangaDirectory);
                File.WriteAllText(mangaDirectory + "\\manga.json", json); // Write the JSON to a file
                File.WriteAllText(mangaDirectory + "\\tracker", "1|1"); // Write initial tracking info to a file
            }
            File.WriteAllText(mangaDirectory + "\\downloading", ""); // Create "Downloading" file

            Manga m = new Manga(mangaName, new DirectoryInfo(mangaDirectory), "1", "1");

            if (!isUpdate)
            {
                DialogResult result = new FrmMangaSettings(m).ShowDialog();
                MessageBox.Show("Downloading data...\nYou may close the Browser as you desire.");
            }
            m.LoadSettings();
            downloadManager.AddMDToQueue(m, contents.chapter, isUpdate);
            RefreshContents();
        }

19 Source : FrmStartPage.cs
with GNU General Public License v3.0
from 9vult

public void AddHentai(string chapterID, string replacedle)
        {
            string hentaiDirectory = homeFolder + "\\h" + chapterID;

            if (!Directory.Exists(hentaiDirectory))
            {
                Logger.Log("Creating directory '" + hentaiDirectory + "' and related files");
                Directory.CreateDirectory(hentaiDirectory);
                File.WriteAllText(hentaiDirectory + "\\tracker", "1|1"); // Write initial tracking info to a file
                File.WriteAllText(hentaiDirectory + "\\replacedle", replacedle); // Write the replacedle to a file
            }
            File.WriteAllText(hentaiDirectory + "\\downloading", ""); // Create "Downloading" file

            Manga m = new Manga("", new DirectoryInfo(hentaiDirectory), "1", "1");
            DialogResult r = new FrmHentaiSettings(m).ShowDialog();

            MessageBox.Show("Downloading data...\nYou may close the Browser as you desire.");

            downloadManager.AddNHToQueue(m, chapterID);
            RefreshContents();
        }

19 Source : ExportingDiagramFixture.cs
with MIT License
from 8T4

protected void Setup(string path = "c4")
        {
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
        }

19 Source : FrmStartPage.cs
with GNU General Public License v3.0
from 9vult

private void FrmStartPage_Load(object sender, EventArgs e)
        {
            downloadManager = new DownloadManager(this);

            if ((string)Properties.Settings.Default["homeDirectory"] == "")
            {
                homeFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MikuReader";
                Properties.Settings.Default["homeDirectory"] = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MikuReader";
                Properties.Settings.Default.Save();
            }
            else
            {
                homeFolder = (string)Properties.Settings.Default["homeDirectory"];
            }

            Logger.logFile = homeFolder + "\\log.txt";

            if (Directory.Exists(homeFolder))
            {
                RefreshContents();
                if (lstManga.Items.Count > 0)
                {
                    lstManga.SelectedIndex = 0;
                }
            }
            else
            {
                Directory.CreateDirectory(homeFolder);
            }

            Logger.Log("Starting Up...");
            Logger.Log("Home folder is '" + homeFolder + "'");

            // updater
            if ((bool)Properties.Settings.Default["checkForUpdates"] == true)
            {
                Logger.Log("Checking for updates...");
                AutoUpdater.Start("https://www.dropbox.com/s/8pf1shiotl68fqv/updateinfo.xml?raw=1");
                AutoUpdater.RunUpdateAsAdmin = true;
                AutoUpdater.DownloadPath = homeFolder + "\\update";
            }

        }

19 Source : CamerasManager.cs
with Apache License 2.0
from A7ocin

void Start() {
      if(enableVideoSave) {
         Time.captureFramerate = frameRate;

         if(cameras.Count > 0) {
            // crea la cartella principale nella quale verranno create una sottocartella per ogni telecamera
            folder = folder + System.DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss");
            if(System.IO.Directory.Exists(folder)) {
               System.IO.Directory.Delete(folder, true);
            }
            System.IO.Directory.CreateDirectory(folder);

            // crea una sottocartella per ogni telecamera
            for(int i = 0; i < cameras.Count; ++i) {
               if(cameras[i].Camera) {
                  cameras[i].Folder = string.Format("{0}/{1}_{2}x{3}_{4}fps",
                                                     folder,
                                                     cameras[i].Name,
                                                     cameras[i].Camera.rect.width,
                                                     cameras[i].Camera.rect.height,
                                                     frameRate);
                  System.IO.Directory.CreateDirectory(cameras[i].Folder);
               }
            }
         }
      }
   }

19 Source : WavUtility.cs
with GNU General Public License v3.0
from a2659802

public static byte[] FromAudioClip(AudioClip audioClip, out string filepath, bool saveAsFile = true, string dirname = "recordings")
		{
			MemoryStream stream = new MemoryStream();

			const int headerSize = 44;

			// get bit depth
			UInt16 bitDepth = 16; //BitDepth (audioClip);

			// NB: Only supports 16 bit
			//Debug.replacedertFormat (bitDepth == 16, "Only converting 16 bit is currently supported. The audio clip data is {0} bit.", bitDepth);

			// total file size = 44 bytes for header format and audioClip.samples * factor due to float to Int16 / sbyte conversion
			int fileSize = audioClip.samples * BlockSize_16Bit + headerSize; // BlockSize (bitDepth)

			// chunk descriptor (riff)
			WriteFileHeader(ref stream, fileSize);
			// file header (fmt)
			WriteFileFormat(ref stream, audioClip.channels, audioClip.frequency, bitDepth);
			// data chunks (data)
			WriteFileData(ref stream, audioClip, bitDepth);

			byte[] bytes = stream.ToArray();

			// Validate total bytes
			Debug.replacedertFormat(bytes.Length == fileSize, "Unexpected AudioClip to wav format byte count: {0} == {1}", bytes.Length, fileSize);

			// Save file to persistant storage location
			if (saveAsFile)
			{
				filepath = string.Format("{0}/{1}/{2}.{3}", Application.persistentDataPath, dirname, DateTime.UtcNow.ToString("yyMMdd-HHmmss-fff"), "wav");
				Directory.CreateDirectory(Path.GetDirectoryName(filepath));
				File.WriteAllBytes(filepath, bytes);
				//Debug.Log ("Auto-saved .wav file: " + filepath);
			}
			else
			{
				filepath = null;
			}

			stream.Dispose();

			return bytes;
		}

19 Source : Tracking.cs
with Apache License 2.0
from A7ocin

void Start()
    {

        ss = 0;
        if (SaveVideoElaborated)
        {
            folder = folder + System.DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss");
            if (System.IO.Directory.Exists(folder))
            {
                System.IO.Directory.Delete(folder, true);
            }
            System.IO.Directory.CreateDirectory(folder);
        }
        x_coordinate = 0;
        y_coordinate = 0;

        skipFrame = 0;
        roiRect = null;

        termination = new TermCriteria(TermCriteria.EPS | TermCriteria.COUNT, 10, 1);


        #if UNITY_WEBGL && !UNITY_EDITOR
                            StartCoroutine(Utils.getFilePathAsync("blobparams.yml", (result) => {
                                blobparams_yml_filepath = result;
                            }));
        #else
                blobparams_yml_filepath = Utils.getFilePath("blobparams.yml");
                //Debug.Log(blobparams_yml_filepath);
        #endif

    }

19 Source : FileUtils.cs
with Apache License 2.0
from A7ocin

public static void EnsurePath(string path)
		{
			if (System.IO.Directory.Exists(path)) return;
			System.IO.Directory.CreateDirectory(path);
		}

19 Source : FileUtils.cs
with Apache License 2.0
from A7ocin

public static string GetInternalDataStoreFolder(bool fullPath = false, bool editorOnly = true)
		{
			var settingsFolderPath = "";
			if (fullPath)
				settingsFolderPath = Path.Combine(Application.dataPath, Path.Combine("UMA", "InternalDataStore"));
			else
				settingsFolderPath = Path.Combine("replacedets", Path.Combine("UMA", "InternalDataStore"));
			if (editorOnly)
			{
				settingsFolderPath = Path.Combine(settingsFolderPath, "InEditor");
			}
			else
			{
				settingsFolderPath = Path.Combine(settingsFolderPath, Path.Combine("InGame", "Resources"));
			}
			if (!Directory.Exists(settingsFolderPath))
				Directory.CreateDirectory(settingsFolderPath);
			if (fullPath)
				settingsFolderPath = Path.GetFullPath(settingsFolderPath);
			return settingsFolderPath;
		}

19 Source : BRDFLookupTextureInspector.cs
with Apache License 2.0
from A7ocin

private static Texture2D PersistLookupTexture (string replacedetName, Texture2D tex)
		{
			if (!System.IO.Directory.Exists (kDirectoryName))
				System.IO.Directory.CreateDirectory (kDirectoryName);	

			string replacedetPath = System.IO.Path.Combine (kDirectoryName, replacedetName + "." + kExtensionName);
			bool newreplacedet = !System.IO.File.Exists (replacedetPath);
			
			System.IO.File.WriteAllBytes (replacedetPath, tex.EncodeToPNG());
			replacedetDatabase.Importreplacedet (replacedetPath, ImportreplacedetOptions.ForceUpdate);

			TextureImporter texSettings = replacedetImporter.GetAtPath (replacedetPath) as TextureImporter;
			if (!texSettings)
			{
				// workaround for bug when importing first generated texture in the project
				replacedetDatabase.Refresh ();
				replacedetDatabase.Importreplacedet (replacedetPath, ImportreplacedetOptions.ForceUpdate);
				texSettings = replacedetImporter.GetAtPath (replacedetPath) as TextureImporter;
			}
			texSettings.textureCompression = TextureImporterCompression.Uncompressed;                             
			texSettings.wrapMode = TextureWrapMode.Clamp;
			if (newreplacedet)
				replacedetDatabase.Importreplacedet (replacedetPath, ImportreplacedetOptions.ForceUpdate);
			
			replacedetDatabase.Refresh ();
			
			Texture2D newTex = replacedetDatabase.LoadreplacedetAtPath (replacedetPath, typeof(Texture2D)) as Texture2D;		
			return newTex;
		}

19 Source : HistoryViewer.cs
with MIT License
from aabiryukov

[System.Diagnostics.Codereplacedysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
		private void ExecViewHistory(Uri tfsCollectionUri, string sourceControlFolder)
        {
            // gource start arguments
            string arguments;
            string replacedle;
			string avatarsDirectory = null;

            if (m_settigs.PlayMode == VisualizationSettings.PlayModeOption.History)
            {
                replacedle = "History of " + sourceControlFolder;
				var logFile = Path.Combine(FileUtils.GetTempPath(), "TfsHistoryLog.tmp.txt");
	            
	            if (m_settigs.ViewAvatars)
	            {
		            avatarsDirectory = Path.Combine(FileUtils.GetTempPath(), "TfsHistoryLog.tmp.Avatars");
					if (!Directory.Exists(avatarsDirectory))
		            {
			            Directory.CreateDirectory(avatarsDirectory);
		            }
	            }

				bool historyFound;
				bool hasLines;

                using (var waitMessage = new WaitMessage("Connecting to Team Foundation Server...", OnCancelByUser))
                {
                    var progress = waitMessage.CreateProgress("Loading history ({0}% done) ...");

                    hasLines =
                        TfsLogWriter.CreateGourceLogFile(
                            logFile,
							avatarsDirectory,
                            tfsCollectionUri,
                            sourceControlFolder,
                            m_settigs,
                            ref m_canceled,
                            progress.SetValue
                            );

	                historyFound = progress.LastValue > 0;
                    progress.Done();
                }

                if (m_canceled)
					return;

                if (!hasLines)
                {
	                MessageBox.Show(
		                historyFound
			                ? "No items found.\nCheck your filters: 'User name' and 'File type'."
							: "No items found.\nTry to change period of the history (From/To dates).",
		                "TFS History Visualization");
	                return;
                }

	            arguments = string.Format(CultureInfo.InvariantCulture, " \"{0}\" ", logFile);

                // Setting other history settings

                arguments += " --seconds-per-day " + m_settigs.SecondsPerDay.ToString(CultureInfo.InvariantCulture);

                if (m_settigs.TimeScale != VisualizationSettings.TimeScaleOption.None)
                {
                    var optionValue = ConvertToString(m_settigs.TimeScale);
                    if (optionValue != null)
                        arguments += " --time-scale " + optionValue;
                }

                if (m_settigs.LoopPlayback)
                {
                    arguments += " --loop";
                }

				arguments += " --file-idle-time 60"; // 60 is default in gource 0.40 and older. Since 0.41 default 0.
            }
            else
            {
                // PlayMode: Live
                replacedle = "Live changes of " + sourceControlFolder;

                arguments = " --realtime --log-format custom -";
                arguments += " --file-idle-time 28800"; // 8 hours (work day)
            }

            var baseDirectory = Path.GetDirectoryName(System.Reflection.replacedembly.GetExecutingreplacedembly().Location) ??
                                "unknown";


            if (baseDirectory.Contains("Test"))
            {
                baseDirectory += @"\..\..\..\VSExtension";
            }

#if DEBUG
			// baseDirectory = @"C:\Temp\aaaa\уи³пс\";
#endif
            var gourcePath = Path.Combine(baseDirectory, @"Gource\Gource.exe");
            var dataPath = Path.Combine(baseDirectory, @"Data");

            // ******************************************************
            // Configuring Gource command line
            // ******************************************************

            arguments +=
                string.Format(CultureInfo.InvariantCulture, " --highlight-users --replacedle \"{0}\"", replacedle);

			if (m_settigs.ViewLogo != CheckState.Unchecked)
			{
				var logoFile = m_settigs.ViewLogo == CheckState.Indeterminate
					? Path.Combine(dataPath, "Logo.png")
					: m_settigs.LogoFileName;

				// fix gource unicode path problems
				logoFile = FileUtils.GetShortPath(logoFile);

				arguments += string.Format(CultureInfo.InvariantCulture, " --logo \"{0}\"", logoFile);
			}

            if (m_settigs.FullScreen)
            {
                arguments += " --fullscreen";

				// By default gource not using full area of screen width ( It's a bug. Must be fixed in gource 0.41).
				// Fixing fullscreen resolution to real full screen.
				if (!m_settigs.SetResolution)
				{
					var screenBounds = Screen.PrimaryScreen.Bounds;
					arguments += string.Format(CultureInfo.InvariantCulture, " --viewport {0}x{1}", screenBounds.Width,
											   screenBounds.Height);
				}
			}

            if (m_settigs.SetResolution)
            {
                arguments += string.Format(CultureInfo.InvariantCulture, " --viewport {0}x{1}",
                                           m_settigs.ResolutionWidth, m_settigs.ResolutionHeight);
            }

            if (m_settigs.ViewFilesExtentionMap)
            {
                arguments += " --key";
            }

			if (!string.IsNullOrEmpty(avatarsDirectory))
			{
				arguments += string.Format(CultureInfo.InvariantCulture, " --user-image-dir \"{0}\"", avatarsDirectory);
			}

            // Process "--hide" option
            {
                var hideItems = string.Empty;
                if (!m_settigs.ViewDirNames)
                {
                    hideItems = "dirnames";
                }
                if (!m_settigs.ViewFileNames)
                {
                    if (hideItems.Length > 0) hideItems += ",";
                    hideItems += "filenames";
                }
                if (!m_settigs.ViewUserNames)
                {
                    if (hideItems.Length > 0) hideItems += ",";
                    hideItems += "usernames";
                }

                if (hideItems.Length > 0)
                    arguments += " --hide " + hideItems;
            }

            arguments += " --max-files " + m_settigs.MaxFiles.ToString(CultureInfo.InvariantCulture);

			if (SystemInformation.TerminalServerSession)
			{
				arguments += " --disable-bloom";
			}

			if (m_settigs.PlayMode == VisualizationSettings.PlayModeOption.History)
            {
                var si = new ProcessStartInfo(gourcePath, arguments)
                    {
                        WindowStyle = ProcessWindowStyle.Maximized,
 //                       UseShellExecute = true
					};

                Process.Start(si);
            }
            else
            {
                var logReader = new VersionControlLogReader(tfsCollectionUri, sourceControlFolder, m_settigs.UsersFilter,
                                                     m_settigs.FilesFilter);
                using (new WaitMessage("Connecting to Team Foundation Server..."))
                {
                    logReader.Connect();
                }

                System.Threading.Tasks.Task.Factory.StartNew(() => RunLiveChangesMonitor(logReader, gourcePath, arguments));
            }
        }

19 Source : SCC.cs
with Apache License 2.0
from AantCoder

public static void Init()
        {
            try
            {
                var workPath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
                    , @"..\LocalLow\Ludeon Studios\RimWorld by Ludeon Studios\OnlineCity");
                Directory.CreateDirectory(workPath);
                Loger.PathLog = workPath;
            }
            catch { }

            Loger.Log("Chat Init");
        }

19 Source : FolderTree.cs
with Apache License 2.0
from AantCoder

public static void ReCreateeTree(string rootFolder, FoldersTree folderTree)
        {
            foreach (var subFolder in folderTree.SubDirs)
            {
                // создаем под директорию 
                var fullNameSubDir = Path.Combine(rootFolder, subFolder.directoryName);
                if (!Directory.Exists(fullNameSubDir))
                {
                    Directory.CreateDirectory(fullNameSubDir);
                }

                // для каждой созданной диретории создаем её поддиреторию 
                foreach (var subTree in subFolder.SubDirs)
                {
                    ReCreateeTree(fullNameSubDir, subTree);
                }
            }
        }

19 Source : Repository.cs
with Apache License 2.0
from AantCoder

public void Load()
        {
            bool needResave = false;
            if (!Directory.Exists(SaveFolderDataPlayers))
                Directory.CreateDirectory(SaveFolderDataPlayers);
            if (!File.Exists(SaveFileName))
            {
                Data = new BaseContainer();
                Save();
                Loger.Log("Server Create Data");
            }
            else
            {
                using (var fs = File.OpenRead(SaveFileName))
                {
                    var bf = new BinaryFormatter() { Binder = new ServerCoreSerializationBinder() };
                    Loger.Log("Server Load...");
                    Data = (BaseContainer)bf.Deserialize(fs);
                    //var dataVersion = Data.VersionNum;
                    Loger.Log("Server Version data: " + Data.Version + " Current version: " + MainHelper.VersionInfo);

                    if (Data.Version != MainHelper.VersionInfo || Data.VersionNum < MainHelper.VersionNum + 1)
                    {
                        convertToLastVersion();
                        needResave = true;
                    }

                    if (Data.Orders == null) Data.Orders = new List<OrderTrade>();

                    Data.UpdatePlayersAllDic();

                    Loger.Log("Server Load done. Users " + Data.PlayersAll.Count.ToString() + ": "
                        + Data.PlayersAll.Select(p => p.Public.Login).Aggregate((string)null, (r, i) => (r == null ? "" : r + ", ") + i)
                        );

                    ChatManager.Instance.NewChatManager(Data.MaxIdChat, Data.PlayerSystem.Chats.Keys.First());
                }
            }


            if (needResave)
                Save();
            ChangeData = false;


        }

19 Source : FileChecker.cs
with Apache License 2.0
from AantCoder

private static void restoreFolderTree(string modsDir, FoldersTree foldersTree)
        {
            if (foldersTree.SubDirs == null)
            {
                return;
            }

            foreach (var folder in foldersTree.SubDirs)
            {
                var dirName = Path.Combine(modsDir, folder.directoryName);
                if (!Directory.Exists(dirName))
                {
                    Loger.Log($"Create directory: {dirName}");
                    Directory.CreateDirectory(dirName);
                }

                // check and create subdirs 
                restoreFolderTree(dirName, folder);
            }
        }

19 Source : Program.cs
with Apache License 2.0
from AantCoder

static void Main(string[] args)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // fix error encoding 1252 from encoding with netcore framework

            var defaultPath = args.Length > 0 ? args[0] : "World";
            var workPath = Path.Combine(Directory.GetCurrentDirectory(), defaultPath);
            Directory.CreateDirectory(workPath);

            //Loger.LogMessage += (msg) => Console.WriteLine(msg);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            Manager = new ServerManager();
            if (!Manager.StartPrepare(workPath)) return;

            var th = new Thread(CommandInput);
            th.IsBackground = true;
            th.Start();

            Manager.Start();
        }

19 Source : DateAndSizeRollingFileAppender.cs
with MIT License
from Abc-Arbitrage

private void Open()
        {
            if (FilenameRoot == "")
                throw new ArgumentException("FilenameRoot name was not supplied for RollingFileAppender");

            try
            {
                FilenameRoot = Path.GetFullPath(FilenameRoot);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Could not resolve the full path to the log file", ex);
            }

            var directory = Path.GetDirectoryName(FilenameRoot) ?? throw new ApplicationException($"Could not resolve the directory of {FilenameRoot}");

            if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
            {
                try
                {
                    Directory.CreateDirectory(directory);
                }
                catch (Exception ex)
                {
                    throw new ApplicationException($"Could not create directory for log file '{directory}'", ex);
                }
            }

            FilenameExtension ??= "";
            _rollingFileNumber = FindLastRollingFileNumber(directory);

            OpenStream();
            CheckRollFile(DateTime.UtcNow);
        }

19 Source : ThroughputToFileBench.cs
with MIT License
from Abc-Arbitrage

public static void Run()
        {
            var dir = Path.GetFullPath(Guid.NewGuid().ToString());
            Directory.CreateDirectory(dir);

            try
            {
                Console.WriteLine("Initializing...");

                BasicConfigurator.Configure(
                    new ZeroLogBasicConfiguration
                    {
                        Appenders = { new DateAndSizeRollingFileAppender(Path.Combine(dir, "Output")), },
                        LogEventQueueSize = 1000 * 4096 * 4,
                        LogEventPoolExhaustionStrategy = LogEventPoolExhaustionStrategy.WaitForLogEvent
                    }
                );

                var log = LogManager.GetLogger(typeof(ThroughputToFileBench));
                var duration = TimeSpan.FromSeconds(10);

                Console.WriteLine("Starting...");

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();

                var sw = Stopwatch.StartNew();
                long counter = 0;
                while (sw.Elapsed < duration)
                {
                    counter++;
                    log.Debug().Append("Counter is: ").Append(counter).Log();
                }

                Console.WriteLine($"Log events: {counter:N0}, Time to append: {sw.Elapsed}");
                Console.WriteLine("Flushing...");
                LogManager.Shutdown();
                Console.WriteLine($"Time to flush: {sw.Elapsed}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Directory.Delete(dir, true);
            }

            Console.WriteLine("Done");
        }

See More Examples