Here are the examples of the csharp api System.IO.Directory.CreateDirectory(string, System.Security.AccessControl.DirectorySecurity) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1581 Examples
19
View Source File : CelesteNetServerModule.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public virtual void Save(string path = "") {
path = Path.GetFullPath(path.Nullify() ?? FilePath);
Logger.Log(LogLevel.INF, "settings", $"Saving {GetType().Name} to {path}");
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
using (Stream stream = File.OpenWrite(path + ".tmp"))
using (StreamWriter writer = new(stream))
Save(writer);
if (File.Exists(path))
File.Delete(path);
File.Move(path + ".tmp", path);
}
19
View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void SaveRaw<T>(string path, T data) where T : notnull {
lock (GlobalLock) {
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
using (Stream stream = File.OpenWrite(path + ".tmp"))
using (StreamWriter writer = new(stream))
YamlHelper.Serializer.Serialize(writer, data, typeof(T));
if (File.Exists(path))
File.Delete(path);
File.Move(path + ".tmp", path);
}
}
19
View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public override Stream WriteFile(string uid, string name) {
string path = GetUserFilePath(uid, name);
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
if (File.Exists(path))
File.Delete(path);
return File.OpenWrite(path);
}
19
View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
private void InsertFileRaw(string path, Stream stream) {
lock (GlobalLock) {
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
if (File.Exists(path))
File.Delete(path);
Stream target = File.OpenWrite(path);
stream.CopyTo(target);
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 0xd4d
License : MIT License
Project Creator : 0xd4d
static int Main(string[] args) {
try {
switch (System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture) {
case System.Runtime.InteropServices.Architecture.X64:
case System.Runtime.InteropServices.Architecture.X86:
break;
default:
throw new ApplicationException($"Unsupported CPU arch: {System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture}");
}
var jitDasmOptions = CommandLineParser.Parse(args);
if (!string2.IsNullOrEmpty(jitDasmOptions.LoadModule)) {
#if DEBUG
Console.Error.WriteLine($"Trying to jit methods in module '{jitDasmOptions.LoadModule}' but JitDasm is a debug build, not a release build!");
#endif
MethodJitter.JitMethods(jitDasmOptions.LoadModule, jitDasmOptions.TypeFilter, jitDasmOptions.MethodFilter, jitDasmOptions.RunClreplacedConstructors, jitDasmOptions.replacedemblySearchPaths);
}
var (bitness, methods, knownSymbols) = GetMethodsToDisreplacedemble(jitDasmOptions.Pid, jitDasmOptions.ModuleName, jitDasmOptions.TypeFilter, jitDasmOptions.MethodFilter, jitDasmOptions.HeapSearch);
var jobs = GetJobs(methods, jitDasmOptions.OutputDir, jitDasmOptions.FileOutputKind, jitDasmOptions.FilenameFormat, out var baseDir);
if (!string2.IsNullOrEmpty(baseDir))
Directory.CreateDirectory(baseDir);
var sourceDoreplacedentProvider = new SourceDoreplacedentProvider();
using (var mdProvider = new MetadataProvider()) {
var sourceCodeProvider = new SourceCodeProvider(mdProvider, sourceDoreplacedentProvider);
using (var context = new DisasmJobContext(bitness, knownSymbols, sourceCodeProvider, jitDasmOptions.DisreplacedemblerOutputKind, jitDasmOptions.Diffable, jitDasmOptions.ShowAddresses, jitDasmOptions.ShowHexBytes, jitDasmOptions.ShowSourceCode)) {
foreach (var job in jobs)
Disreplacedemble(context, job);
}
}
return 0;
}
catch (ShowCommandLineHelpException) {
CommandLineParser.ShowHelp();
return 1;
}
catch (CommandLineParserException ex) {
Console.WriteLine(ex.Message);
return 1;
}
catch (ApplicationException ex) {
Console.WriteLine(ex.Message);
return 1;
}
catch (ClrDiagnosticsException ex) {
Console.WriteLine(ex.Message);
Console.WriteLine("Make sure this process has the same bitness as the target process");
return 1;
}
catch (Exception ex) {
Console.WriteLine(ex.ToString());
return 1;
}
}
19
View Source File : FileUploadProvider.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public async Task<IResultModel<FileDescriptor>> Upload(FileUploadModel model, CancellationToken cancellationToken = default)
{
Check.NotNull(model, nameof(model), "file upload model is null");
Check.NotNull(model.StorageRootDirectory, nameof(model.StorageRootDirectory), "the file storage root directory is null");
var result = new ResultModel<FileDescriptor>();
if (model.FormFile == null)
return result.Failed("请选择文件!");
var size = model.FormFile.Length;
//验证文件大小
if (model.MaxSize > 0 && model.MaxSize < size)
return result.Failed($"文件大小不能超过{new FileSize(model.MaxSize).ToString()}");
var name = model.FileName.IsNull() ? model.FormFile.FileName : model.FileName;
var descriptor = new FileDescriptor(name, size);
//验证扩展名
if (model.LimitExtensions != null && !model.LimitExtensions.Any(m => m.EqualsIgnoreCase(descriptor.Extension)))
return result.Failed($"文件格式无效,请上传{model.LimitExtensions.Aggregate((x, y) => x + "," + y)}格式的文件");
//按照日期来保存文件
var date = DateTime.Now;
descriptor.DirectoryName = Path.Combine(model.StorageRootDirectory, date.ToString("yyyy"), date.ToString("MM"), date.ToString("dd"));
//创建目录
if (!Directory.Exists(descriptor.DirectoryName))
{
Directory.CreateDirectory(descriptor.DirectoryName);
}
//生成文件存储名称
descriptor.StorageName = $"{Guid.NewGuid().ToString().Replace("-", "")}.{descriptor.Extension}";
//写入
await using var stream = new FileStream(descriptor.FullName, FileMode.Create);
//计算MD5
if (model.CalculateMd5)
{
descriptor.Md5 = _md5Encrypt.Encrypt(stream);
}
await model.FormFile.CopyToAsync(stream, cancellationToken);
return result.Success(descriptor);
}
19
View Source File : FrmLauncher.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
private void FrmLauncher_Load(object sender, EventArgs e)
{
WFClient.logger.Log("Starting");
// Set embedded fonts
label1.Font = bigFont;
label2.Font = smallFont;
if (Properties.Settings.Default["approot"].ToString() == String.Empty)
{
Properties.Settings.Default["approot"] = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MikuReader2");
Properties.Settings.Default.Save();
}
FileHelper.APP_ROOT = FileHelper.CreateDI(Properties.Settings.Default["approot"].ToString());
Directory.CreateDirectory(FileHelper.APP_ROOT.FullName);
WFClient.logger.Log("Loading from " + FileHelper.APP_ROOT);
if (File.Exists(Path.Combine(FileHelper.APP_ROOT.FullName, "mikureader.txt")))
{
SettingsHelper.Initialize();
}
else
{
SettingsHelper.Create();
SettingsHelper.Initialize();
}
WFClient.dlm.ProgressUpdated += new ProgressUpdatedEventHandler(ProgressUpdatedCallback);
RepopulateItems();
if (SettingsHelper.CheckForUpdates)
Updater.Start();
}
19
View Source File : Command.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
if (commandData == null)
{
return Result.Failed;
}
if (!System.IO.Directory.Exists(Constants.DefaultExportDirectory))
{
System.IO.Directory.CreateDirectory(Constants.DefaultExportDirectory);
}
if (string.IsNullOrEmpty(FileUtilities.GetCentralFileName(commandData.Application.ActiveUIDoreplacedent.Doreplacedent)))
{
WindowManager.ShowMessageBox("FAIL", "Please save the file before continuing");
return Result.Failed;
}
var uidoc = commandData.Application.ActiveUIDoreplacedent;
if (uidoc == null)
{
return Result.Failed;
}
var views = new List<ViewSheet>();
if (uidoc.Doreplacedent.ActiveView.ViewType == ViewType.ProjectBrowser)
{
var s = uidoc.Selection.GetElementIds();
foreach (var id in s)
{
var projectBrowserView = uidoc.Doreplacedent.GetElement(id);
if (projectBrowserView is View)
{
var v = (View)projectBrowserView;
if (v.ViewType == ViewType.ProjectBrowser)
{
continue;
}
if (v is ViewSheet)
{
views.Add((ViewSheet)v);
continue;
}
}
}
}
// Deselect all elements before continuing so they don't appear incorrectly
uidoc.Selection.SetElementIds(new List<ElementId>());
var manager = new Manager(uidoc);
var log = new ExportLog();
var vm = new ViewModels.SCexportViewModel(manager, views);
var wm = WindowManager;
wm.ShowDialog(vm, null, ViewModels.SCexportViewModel.DefaultWindowSettings);
if (vm.CloseStatus != ViewModels.SCexportViewModel.CloseMode.Exit)
{
string exportType = string.Empty;
switch (vm.CloseStatus)
{
case ViewModels.SCexportViewModel.CloseMode.Export:
exportType = "Exporting";
break;
case ViewModels.SCexportViewModel.CloseMode.Print:
case ViewModels.SCexportViewModel.CloseMode.PrintA3:
case ViewModels.SCexportViewModel.CloseMode.PrintA2:
exportType = "Printing";
break;
}
var progressVm = new ViewModels.ProgressMonitorViewModel
{
MaximumValue = vm.SelectedSheets.Count, Value = 0
};
log.Clear();
log.Start(exportType + " Started.");
WindowManager.ShowWindow(progressVm, null, ViewModels.ProgressMonitorViewModel.DefaultWindowSettings);
if (manager.SaveHistory)
{
RecentExport.Save(manager, vm.SelectedSheets);
}
foreach (var sheet in vm.SelectedSheets)
{
progressVm.ProgressSummary += @" --> " + exportType + @" " + sheet.FullExportName + "...";
switch (vm.CloseStatus)
{
case ViewModels.SCexportViewModel.CloseMode.Export:
manager.ExportSheet(sheet, log);
break;
case ViewModels.SCexportViewModel.CloseMode.Print:
manager.Print(sheet, manager.PrinterNameLargeFormat, 1, log);
break;
case ViewModels.SCexportViewModel.CloseMode.PrintA3:
manager.Print(sheet, manager.PrinterNameA3, 3, log);
break;
case ViewModels.SCexportViewModel.CloseMode.PrintA2:
manager.Print(sheet, manager.PrinterNameLargeFormat, 2, log);
break;
default:
return Result.Succeeded;
}
progressVm.Value++;
string niceTime = string.Format(
System.Globalization.CultureInfo.CurrentCulture,
"OK [ time {0:hh\\.mm\\:ss} total {1:hh\\.mm\\:ss} ~remaining {2:hh\\.mm\\:ss}]",
log.LasreplacedemElapsedTime,
log.TimeSinceStart,
System.TimeSpan.FromTicks(log.TimeSinceStart.Ticks / progressVm.Value * (progressVm.MaximumValue - progressVm.Value)));
progressVm.ProgressSummary += niceTime + System.Environment.NewLine;
if (progressVm.CancelPressed)
{
break;
}
}
log.Stop("Finished");
progressVm.Stop(log);
progressVm.ProcessComplete = true;
}
if (manager.ShowExportLog || log.Errors > 0) {
var exportLogViewModel = new ViewModels.ExportLogViewModel(log);
WindowManager.ShowDialog(exportLogViewModel, null, ViewModels.ExportLogViewModel.DefaultWindowSettings);
}
return Result.Succeeded;
}
19
View Source File : OutputManagerL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async void MatcherFile()
{
Environment.SetEnvironmentVariable("RUNNER_TEST_GET_REPOSITORY_PATH_FAILSAFE", "2");
var matchers = new IssueMatchersConfig
{
Matchers =
{
new IssueMatcherConfig
{
Owner = "my-matcher-1",
Patterns = new[]
{
new IssuePatternConfig
{
Pattern = @"(.+): (.+)",
File = 1,
Message = 2,
},
},
},
},
};
using (var hostContext = Setup(matchers: matchers))
using (_outputManager)
{
// Setup github.workspace, github.repository
var workDirectory = hostContext.GetDirectory(WellKnownDirectory.Work);
ArgUtil.NotNullOrEmpty(workDirectory, nameof(workDirectory));
Directory.CreateDirectory(workDirectory);
var workspaceDirectory = Path.Combine(workDirectory, "workspace");
Directory.CreateDirectory(workspaceDirectory);
_executionContext.Setup(x => x.GetGitHubContext("workspace")).Returns(workspaceDirectory);
_executionContext.Setup(x => x.GetGitHubContext("repository")).Returns("my-org/workflow-repo");
// Setup some git repositories
// <WORKSPACE>/workflow-repo
// <WORKSPACE>/workflow-repo/nested-other-repo
// <WORKSPACE>/other-repo
// <WORKSPACE>/other-repo/nested-workflow-repo
// <WORKSPACE>/workflow-repo-using-ssh
var workflowRepository = Path.Combine(workspaceDirectory, "workflow-repo");
var nestedOtherRepository = Path.Combine(workspaceDirectory, "workflow-repo", "nested-other-repo");
var otherRepository = Path.Combine(workspaceDirectory, workflowRepository, "nested-other-repo");
var nestedWorkflowRepository = Path.Combine(workspaceDirectory, "other-repo", "nested-workflow-repo");
var workflowRepositoryUsingSsh = Path.Combine(workspaceDirectory, "workflow-repo-using-ssh");
await CreateRepository(hostContext, workflowRepository, "https://github.com/my-org/workflow-repo");
await CreateRepository(hostContext, nestedOtherRepository, "https://github.com/my-org/other-repo");
await CreateRepository(hostContext, otherRepository, "https://github.com/my-org/other-repo");
await CreateRepository(hostContext, nestedWorkflowRepository, "https://github.com/my-org/workflow-repo");
await CreateRepository(hostContext, workflowRepositoryUsingSsh, "[email protected]:my-org/workflow-repo.git");
// Create test files
var file_noRepository = Path.Combine(workspaceDirectory, "no-repo.txt");
var file_workflowRepository = Path.Combine(workflowRepository, "workflow-repo.txt");
var file_workflowRepository_nestedDirectory = Path.Combine(workflowRepository, "subdir", "subdir2", "workflow-repo-nested-dir.txt");
var file_workflowRepository_failsafe = Path.Combine(workflowRepository, "failsafe-subdir", "failsafe-subdir2", "failsafe-subdir3", "workflow-repo-failsafe.txt");
var file_nestedOtherRepository = Path.Combine(nestedOtherRepository, "nested-other-repo");
var file_otherRepository = Path.Combine(otherRepository, "other-repo.txt");
var file_nestedWorkflowRepository = Path.Combine(nestedWorkflowRepository, "nested-workflow-repo.txt");
var file_workflowRepositoryUsingSsh = Path.Combine(workflowRepositoryUsingSsh, "workflow-repo-using-ssh.txt");
foreach (var file in new[] { file_noRepository, file_workflowRepository, file_workflowRepository_nestedDirectory, file_workflowRepository_failsafe, file_nestedOtherRepository, file_otherRepository, file_nestedWorkflowRepository, file_workflowRepositoryUsingSsh })
{
Directory.CreateDirectory(Path.GetDirectoryName(file));
File.WriteAllText(file, "");
}
// Process
Process($"{file_noRepository}: some error 1");
Process($"{file_workflowRepository}: some error 2");
Process($"{file_workflowRepository.Substring(workspaceDirectory.Length + 1)}: some error 3"); // Relative path from workspace dir
Process($"{file_workflowRepository_nestedDirectory}: some error 4");
Process($"{file_workflowRepository_failsafe}: some error 5");
Process($"{file_nestedOtherRepository}: some error 6");
Process($"{file_otherRepository}: some error 7");
Process($"{file_nestedWorkflowRepository}: some error 8");
Process($"{file_workflowRepositoryUsingSsh}: some error 9");
replacedert.Equal(9, _issues.Count);
replacedert.Equal("some error 1", _issues[0].Item1.Message);
replacedert.False(_issues[0].Item1.Data.ContainsKey("file"));
replacedert.Equal("some error 2", _issues[1].Item1.Message);
replacedert.Equal(file_workflowRepository.Substring(workflowRepository.Length + 1).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), _issues[1].Item1.Data["file"]);
replacedert.Equal("some error 3", _issues[2].Item1.Message);
replacedert.Equal(file_workflowRepository.Substring(workflowRepository.Length + 1).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), _issues[2].Item1.Data["file"]);
replacedert.Equal("some error 4", _issues[3].Item1.Message);
replacedert.Equal(file_workflowRepository_nestedDirectory.Substring(workflowRepository.Length + 1).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), _issues[3].Item1.Data["file"]);
replacedert.Equal("some error 5", _issues[4].Item1.Message);
replacedert.False(_issues[4].Item1.Data.ContainsKey("file"));
replacedert.Equal("some error 6", _issues[5].Item1.Message);
replacedert.False(_issues[5].Item1.Data.ContainsKey("file"));
replacedert.Equal("some error 7", _issues[6].Item1.Message);
replacedert.False(_issues[6].Item1.Data.ContainsKey("file"));
replacedert.Equal("some error 8", _issues[7].Item1.Message);
replacedert.Equal(file_nestedWorkflowRepository.Substring(nestedWorkflowRepository.Length + 1).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), _issues[7].Item1.Data["file"]);
replacedert.Equal("some error 9", _issues[8].Item1.Message);
replacedert.Equal(file_workflowRepositoryUsingSsh.Substring(workflowRepositoryUsingSsh.Length + 1).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), _issues[8].Item1.Data["file"]);
}
Environment.SetEnvironmentVariable("RUNNER_TEST_GET_REPOSITORY_PATH_FAILSAFE", "");
}
19
View Source File : ActionCommandManagerL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void AddMatcherTranslatesFilePath()
{
using (TestHostContext hc = CreateTestContext())
{
// Create a problem matcher config file
var hostDirectory = hc.GetDirectory(WellKnownDirectory.Temp);
var hostFile = Path.Combine(hostDirectory, "my-matcher.json");
Directory.CreateDirectory(hostDirectory);
var content = @"
{
""problemMatcher"": [
{
""owner"": ""my-matcher"",
""pattern"": [
{
""regexp"": ""^ERROR: (.+)$"",
""message"": 1
}
]
}
]
}";
File.WriteAllText(hostFile, content);
// Setup translation info
var container = new ContainerInfo();
var containerDirectory = "/some-container-directory";
var containerFile = Path.Combine(containerDirectory, "my-matcher.json");
container.AddPathTranslateMapping(hostDirectory, containerDirectory);
// Act
_commandManager.TryProcessCommand(_ec.Object, $"::add-matcher::{containerFile}", container);
// replacedert
_ec.Verify(x => x.AddMatchers(It.IsAny<IssueMatchersConfig>()), Times.Once);
}
}
19
View Source File : SetEnvFileCommandL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private TestHostContext Setup([CallerMemberName] string name = "")
{
_issues = new List<Tuple<DTWebApi.Issue, string>>();
var hostContext = new TestHostContext(this, name);
// Trace
_trace = hostContext.GetTrace();
// Directory for test data
var workDirectory = hostContext.GetDirectory(WellKnownDirectory.Work);
ArgUtil.NotNullOrEmpty(workDirectory, nameof(workDirectory));
Directory.CreateDirectory(workDirectory);
_rootDirectory = Path.Combine(workDirectory, nameof(SetEnvFileCommandL0));
Directory.CreateDirectory(_rootDirectory);
// Execution context
_executionContext = new Mock<IExecutionContext>();
_executionContext.Setup(x => x.Global)
.Returns(new GlobalContext
{
EnvironmentVariables = new Dictionary<string, string>(VarUtil.EnvironmentVariableKeyComparer),
WriteDebug = true,
});
_executionContext.Setup(x => x.AddIssue(It.IsAny<DTWebApi.Issue>(), It.IsAny<string>()))
.Callback((DTWebApi.Issue issue, string logMessage) =>
{
_issues.Add(new Tuple<DTWebApi.Issue, string>(issue, logMessage));
var message = !string.IsNullOrEmpty(logMessage) ? logMessage : issue.Message;
_trace.Info($"Issue '{issue.Type}': {message}");
});
_executionContext.Setup(x => x.Write(It.IsAny<string>(), It.IsAny<string>()))
.Callback((string tag, string message) =>
{
_trace.Info($"{tag}{message}");
});
// SetEnvFileCommand
_setEnvFileCommand = new SetEnvFileCommand();
_setEnvFileCommand.Initialize(hostContext);
return hostContext;
}
19
View Source File : OutputManagerL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async void MatcherFromPath()
{
var matchers = new IssueMatchersConfig
{
Matchers =
{
new IssueMatcherConfig
{
Owner = "my-matcher-1",
Patterns = new[]
{
new IssuePatternConfig
{
Pattern = @"(.+): (.+) \[(.+)\]",
File = 1,
Message = 2,
FromPath = 3,
},
},
},
},
};
using (var hostContext = Setup(matchers: matchers))
using (_outputManager)
{
// Setup github.workspace, github.repository
var workDirectory = hostContext.GetDirectory(WellKnownDirectory.Work);
ArgUtil.NotNullOrEmpty(workDirectory, nameof(workDirectory));
Directory.CreateDirectory(workDirectory);
var workspaceDirectory = Path.Combine(workDirectory, "workspace");
Directory.CreateDirectory(workspaceDirectory);
_executionContext.Setup(x => x.GetGitHubContext("workspace")).Returns(workspaceDirectory);
_executionContext.Setup(x => x.GetGitHubContext("repository")).Returns("my-org/workflow-repo");
// Setup a git repository
var repositoryPath = Path.Combine(workspaceDirectory, "workflow-repo");
await CreateRepository(hostContext, repositoryPath, "https://github.com/my-org/workflow-repo");
// Create a test file
var filePath = Path.Combine(repositoryPath, "some-project", "some-directory", "some-file.txt");
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
File.WriteAllText(filePath, "");
// Process
Process("some-directory/some-file.txt: some error [workflow-repo/some-project/some-project.proj]");
replacedert.Equal(1, _issues.Count);
replacedert.Equal("some error", _issues[0].Item1.Message);
replacedert.Equal("some-project/some-directory/some-file.txt", _issues[0].Item1.Data["file"]);
replacedert.Equal(0, _commands.Count);
replacedert.Equal(0, _messages.Count);
}
}
19
View Source File : MainWindow.cs
License : MIT License
Project Creator : adainrivers
License : MIT License
Project Creator : adainrivers
private async void MainForm_Load(object sender, EventArgs e)
{
FromImageButton.Visible = true;
PerformanceGrid.Visible = true;
PerformanceLabel.Visible = true;
Region.DataSource = Servers.GetRegions();
RegisterHotKeys();
LoadConfiguration();
UpdateServersVisibility();
if (!string.IsNullOrWhiteSpace(Region.Text))
{
var selectedServer = Server.Text;
Server.DataSource = Servers.GetServers(Region.Text);
Server.Text = selectedServer;
}
if (!Directory.Exists(Constants.DebugFolder))
{
Directory.CreateDirectory(Constants.DebugFolder);
}
await CheckForUpdate();
}
19
View Source File : Program.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
private static void InitializeDirectory()
{
foreach (var dir in TelegramBotSettings.DIRS_TO_INITALIZE)
{
try
{
if (!System.IO.Directory.Exists(dir))
System.IO.Directory.CreateDirectory(dir);
}
catch (Exception ex)
{
Console.WriteLine($"[INITIALIZATION ERROR] {ex.Message}");
throw ex;
}
}
}
19
View Source File : AudioFile.cs
License : MIT License
Project Creator : adlez27
License : MIT License
Project Creator : adlez27
public void Write()
{
Directory.CreateDirectory(settings.DestinationFolder);
if (recorded)
{
byte[] temp = new byte[Data.Length * 2];
System.Buffer.BlockCopy(Data, 0, temp, 0, Data.Length * 2);
Write(temp, FullName);
}
}
19
View Source File : ConvertCommand.cs
License : MIT License
Project Creator : AdrianWilczynski
License : MIT License
Project Creator : AdrianWilczynski
private void CreateOrUpdateFile(string path, string content, bool partialOverride)
{
Directory.CreateDirectory(path.ContainingDirectory());
if (partialOverride)
{
content = Marker.Update(File.Exists(path) ? File.ReadAllText(path) : string.Empty, content);
}
File.WriteAllText(path, content);
}
19
View Source File : ConvertCommandShould.cs
License : MIT License
Project Creator : AdrianWilczynski
License : MIT License
Project Creator : AdrianWilczynski
[Fact]
public void ClearOutputDirectory()
{
Prepare(nameof(ClearOutputDirectory));
var originalFilePath = Path.Join(nameof(ClearOutputDirectory), "Item.cs");
var outputDirectoryPath = Path.Join(nameof(ClearOutputDirectory), "Output");
var undesiredFilePath = Path.Join(outputDirectoryPath, "garbage.ts");
Directory.CreateDirectory(outputDirectoryPath);
File.WriteAllText(originalFilePath, "clreplaced Item11 { }");
File.WriteAllText(undesiredFilePath, "export interface Garbage { }");
_convertCommand.Input = originalFilePath;
_convertCommand.Output = outputDirectoryPath;
_convertCommand.ClearOutputDirectory = true;
_convertCommand.OnExecute();
replacedert.False(File.Exists(undesiredFilePath));
}
19
View Source File : ConvertCommandShould.cs
License : MIT License
Project Creator : AdrianWilczynski
License : MIT License
Project Creator : AdrianWilczynski
[Fact]
public void IgnoreClearOutputSettingIfUnsafe()
{
Prepare(nameof(IgnoreClearOutputSettingIfUnsafe));
var outputDirectoryPath = Path.Join(nameof(IgnoreClearOutputSettingIfUnsafe), "Parrent");
var inputDirectoryPath = Path.Join(outputDirectoryPath, "Input");
Directory.CreateDirectory(outputDirectoryPath);
Directory.CreateDirectory(inputDirectoryPath);
var undesiredFilePath = Path.Join(outputDirectoryPath, "garbage.ts");
File.WriteAllText(undesiredFilePath, "export interface Garbage { }");
_convertCommand.Input = inputDirectoryPath;
_convertCommand.Output = outputDirectoryPath;
_convertCommand.ClearOutputDirectory = true;
_convertCommand.OnExecute();
replacedert.True(File.Exists(undesiredFilePath));
undesiredFilePath = Path.Join(inputDirectoryPath, "trash.ts");
File.WriteAllText(undesiredFilePath, "export interface Trash { }");
_convertCommand.Output = inputDirectoryPath;
_convertCommand.OnExecute();
replacedert.True(File.Exists(undesiredFilePath));
}
19
View Source File : ConvertCommandShould.cs
License : MIT License
Project Creator : AdrianWilczynski
License : MIT License
Project Creator : AdrianWilczynski
[Fact]
public void ConvertFilesInNestedDirecotories()
{
Prepare(nameof(ConvertFilesInNestedDirecotories));
var sourceFilePath = Path.Join(nameof(ConvertFilesInNestedDirecotories), "Item.cs");
var nestedDirectoryPath = Path.Join(nameof(ConvertFilesInNestedDirecotories), "Nested");
var nestedSourceFilePath = Path.Join(nestedDirectoryPath, "NestedItem.cs");
File.WriteAllText(sourceFilePath, "clreplaced Item13 { }");
Directory.CreateDirectory(nestedDirectoryPath);
File.WriteAllText(nestedSourceFilePath, "clreplaced Item14 { }");
_convertCommand.Input = nameof(ConvertFilesInNestedDirecotories);
_convertCommand.OnExecute();
var outputFilePath = Path.Join(nameof(ConvertFilesInNestedDirecotories), "item.ts");
var nestedOutputFilePath = Path.Join(nestedDirectoryPath, "nestedItem.ts");
replacedert.True(File.Exists(outputFilePath));
replacedert.True(File.Exists(nestedOutputFilePath));
}
19
View Source File : ConvertCommandShould.cs
License : MIT License
Project Creator : AdrianWilczynski
License : MIT License
Project Creator : AdrianWilczynski
[Fact]
public void ConvertDirectoryIntoProvidedOutputDirectory()
{
Prepare(nameof(ConvertDirectoryIntoProvidedOutputDirectory));
var inputDirectoryPath = Path.Join(nameof(ConvertDirectoryIntoProvidedOutputDirectory), "Input");
Directory.CreateDirectory(inputDirectoryPath);
Directory.SetCurrentDirectory(inputDirectoryPath);
try
{
File.WriteAllText("File1.cs", "clreplaced Item8 { }");
File.WriteAllText("File2.cs", "clreplaced Item9 { }");
File.WriteAllText("File3.cs", "clreplaced Item10 { }");
var outputDirectoryPath = Path.Join("..", "Output");
_convertCommand.Input = ".";
_convertCommand.Output = outputDirectoryPath;
_convertCommand.OnExecute();
var convertedFiles = Directory.GetFiles(outputDirectoryPath)
.Where(f => f.EndsWith(".ts"))
.Select(Path.GetFileName);
replacedert.Equal(new[] { "file1.ts", "file2.ts", "file3.ts" }, convertedFiles);
}
finally
{
Directory.SetCurrentDirectory(Path.Join("..", ".."));
}
}
19
View Source File : MarkPhase.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a
License : GNU General Public License v3.0
Project Creator : Aekras1a
public void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e)
{
var writer = (ModuleWriter) sender;
if(commitListener != null)
commitListener.OnWriterEvent(writer, e.WriterEvent);
if(e.WriterEvent == ModuleWriterEvent.MDBeginWriteMethodBodies && methods.ContainsKey(writer.Module))
{
vr.ProcessMethods(writer.Module, (num, total) =>
{
ctx.Logger.Progress(num, total);
ctx.CheckCancellation();
});
ctx.Logger.EndProgress();
foreach(var repl in refRepl)
vr.Runtime.Descriptor.Data.ReplaceReference(repl.Key, repl.Value);
commitListener = vr.CommitModule(ctx.CurrentModule, (num, total) =>
{
ctx.Logger.Progress(num, total);
ctx.CheckCancellation();
});
}
else if(commitListener != null && e.WriterEvent == ModuleWriterEvent.End && vr.ExportDbgInfo)
{
var mapName = Path.ChangeExtension(writer.Module.Name, "map");
var mapPath = Path.GetFullPath(Path.Combine(ctx.OutputDirectory, mapName));
Directory.CreateDirectory(ctx.OutputDirectory);
File.WriteAllBytes(mapPath, vr.Runtime.DebugInfo);
}
}
19
View Source File : StickersExport.cs
License : MIT License
Project Creator : agens-no
License : MIT License
Project Creator : agens-no
private static void ExportStickerSequence(string pathToStickers, Sticker stickerSequence, string pathToProject)
{
var pathToSticker = pathToStickers + "/" + stickerSequence.Name + ".stickersequence";
if (Directory.Exists(pathToSticker))
{
Directory.Delete(pathToSticker, true);
}
Directory.CreateDirectory(pathToSticker);
var json = CreateStickerSequenceContent(stickerSequence);
Log("writing " + pathToSticker + "/Contents.json");
json.WriteToFile(pathToSticker + "/Contents.json");
foreach (var frame in stickerSequence.Frames)
{
var oldPath = pathToProject + "/" + replacedetDatabase.GetreplacedetPath(frame);
var fileName = pathToSticker + "/" + frame.name + ".png";
File.Copy(oldPath, fileName);
}
}
19
View Source File : StickersExport.cs
License : MIT License
Project Creator : agens-no
License : MIT License
Project Creator : agens-no
private static void ExportSticker(string pathToStickers, Sticker sticker, string pathToProject)
{
if (sticker == null || sticker.Frames[0] == null) return;
var stickerTexture = sticker.Frames[0];
var pathToSticker = pathToStickers + "/" + sticker.Name + ".sticker";
if (Directory.Exists(pathToSticker))
{
Directory.Delete(pathToSticker, true);
}
Directory.CreateDirectory(pathToSticker);
var unityreplacedetPath = pathToProject + "/" + replacedetDatabase.GetreplacedetPath(stickerTexture);
var newFileName = sticker.Name;
var fileExtension = Path.GetExtension(unityreplacedetPath);
var json = CreateStickerContent(newFileName + fileExtension);
Log("writing " + pathToSticker + "/Contents.json");
json.WriteToFile(pathToSticker + "/Contents.json");
var xcodereplacedetPath = pathToSticker + "/" + newFileName + fileExtension;
var count = 0;
while (File.Exists(xcodereplacedetPath))
{
xcodereplacedetPath = pathToSticker + "/" + newFileName + count.ToString() + fileExtension;
}
File.Copy(unityreplacedetPath, xcodereplacedetPath);
}
19
View Source File : PathUtils.cs
License : MIT License
Project Creator : aguang-xyz
License : MIT License
Project Creator : aguang-xyz
public static string GetCacheFileName(string type, string url)
{
var path = Path.Join(CacheFolder, type);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
return Path.Join(path, Base64Utils.ToBase64(url).Replace("/", "_"));
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : ahmed605
License : GNU General Public License v3.0
Project Creator : ahmed605
private void ExtractToPath(Directory dir, string path)
{
foreach (var item in dir)
{
if (item.IsDirectory)
{
try
{
IODirectory.CreateDirectory(path + item.Name);
ExtractToPath(item as Directory, path + item.Name + "\\");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
File file = item as File;
byte[] data = file.GetData();
IOFile.WriteAllBytes(Path.Combine(path, file.Name), data);
}
}
}
19
View Source File : OptionsExtensions.cs
License : MIT License
Project Creator : ai-traders
License : MIT License
Project Creator : ai-traders
public static void EnsureValid(this FileSystemStorageOptions options)
{
if (options == null) ThrowMissingConfiguration(nameof(LiGetOptions.Storage));
options.Path = string.IsNullOrEmpty(options.Path)
? Path.Combine(Directory.GetCurrentDirectory(), "Packages")
: options.Path;
// Ensure the package storage directory exists
Directory.CreateDirectory(options.Path);
}
19
View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
public int ExportDir(ICollection<ItemModel> fis, string path, Stream stream)
{
int count = 0;
Directory.CreateDirectory(path);
foreach (var fi in fis)
{
var fr = fi.Record as FileRecord;
if (fr == null) // is directory
{
Directory.CreateDirectory(path + "\\" + fi.Name);
count += ExportDir(fi.ChildItems, path + "\\" + fi.Name, stream);
}
else // is file
{
File.WriteAllBytes(path + "\\" + fi.Name, fr.Read(stream));
count++;
}
}
return count;
}
19
View Source File : ServiceInstaller.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static void SetDirectoryPermission()
{
if (!Directory.Exists(CacheManager.CachePath))
Directory.CreateDirectory(CacheManager.CachePath);
FileSystemRights rights = FileSystemRights.CreateDirectories | FileSystemRights.CreateFiles | FileSystemRights.Read | FileSystemRights.Write;
DirectorySecurity sec = new DirectorySecurity();
sec.AddAccessRule(new FileSystemAccessRule("Everyone", rights,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
System.IO.Directory.SetAccessControl(CacheManager.CachePath, sec);
System.IO.Directory.SetAccessControl(bfbd.UltraRecord.Client.LocalStorage.DataPath, sec);
#if !DEBUG
new DirectoryInfo(Application.StartupPath).Attributes |= FileAttributes.System | FileAttributes.Hidden;
new DirectoryInfo(Path.GetDirectoryName(Application.StartupPath)).Attributes |= FileAttributes.System | FileAttributes.Hidden;
#endif
}
19
View Source File : ContentsBrowser.cs
License : MIT License
Project Creator : alaabenfatma
License : MIT License
Project Creator : alaabenfatma
private void NewItemMenu(MenuItem item)
{
var folder_tb = new TextBlock();
folder_tb.Inlines.Add(new Run("📁")
{
Foreground = Brushes.LightGoldenrodYellow,
FontSize = 16,
FontFamily = new FontFamily("Vendana")
});
folder_tb.Inlines.Add(new Run(" New Folder.") {Foreground = Brushes.White});
var file_tb = new TextBlock();
file_tb.Inlines.Add(new Run("🗋")
{
Foreground = Brushes.LightGoldenrodYellow,
FontSize = 16,
FontFamily = new FontFamily("Vendana")
});
file_tb.Inlines.Add(new Run(" New Folder.") {Foreground = Brushes.White});
var folder = new MenuItem
{
Header = folder_tb
};
folder.Click += (s, e) =>
{
var name = MagicLaboratory.RandomString(6);
Directory.CreateDirectory(Item.Path + @"\" + name);
Item.AddFolder(name, "", Item.Path + @"\" + name);
Dispatcher.BeginInvoke(DispatcherPriority.Loaded,
new Action(() => { Item.Items[Item.Items.Count - 1].Rename("New folder..."); }));
};
var file = new MenuItem
{
Header = file_tb
};
item.Items.Add(folder);
item.Items.Add(file);
}
19
View Source File : ResourceExporter.cs
License : MIT License
Project Creator : Albeoris
License : MIT License
Project Creator : Albeoris
private static void PrepareDirectory(String fullPath)
{
Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!);
}
19
View Source File : AppDataService.cs
License : MIT License
Project Creator : Aleksbgbg
License : MIT License
Project Creator : Aleksbgbg
public string GetFolder(string name)
{
string directoryPath = Path.Combine(ApplicationPath, name);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
return directoryPath;
}
19
View Source File : AppDataService.cs
License : MIT License
Project Creator : Aleksbgbg
License : MIT License
Project Creator : Aleksbgbg
public string GetFile(string name, Func<string> defaultContents)
{
string filePath = Path.Combine(ApplicationPath, name);
if (!File.Exists(filePath))
{
string directory = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
File.WriteAllText(filePath, defaultContents());
}
return filePath;
}
19
View Source File : MapboxConfigurationWindow.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
static void Init()
{
Runnable.EnableRunnableInEditor();
//verify that the config file exists
_configurationFile = Path.Combine(Unity.Constants.Path.MAPBOX_RESOURCES_ABSOLUTE, Unity.Constants.Path.CONFIG_FILE);
if (!Directory.Exists(Unity.Constants.Path.MAPBOX_RESOURCES_ABSOLUTE))
{
Directory.CreateDirectory(Unity.Constants.Path.MAPBOX_RESOURCES_ABSOLUTE);
}
if (!File.Exists(_configurationFile))
{
_mapboxConfig = new MapboxConfiguration
{
AccessToken = _accessToken,
MemoryCacheSize = (uint)_memoryCacheSize,
FileCacheSize = (uint)_fileCacheSize,
AutoRefreshCache = _autoRefreshCache,
DefaultTimeout = _webRequestTimeout
};
var json = JsonUtility.ToJson(_mapboxConfig);
File.WriteAllText(_configurationFile, json);
replacedetDatabase.Refresh();
}
//finish opening the window after the replacedetdatabase is refreshed.
EditorApplication.delayCall += OpenWindow;
}
19
View Source File : BuildProcessCallbacksHandler.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
private static void PostBuildInternal( string agxDynamicsPath,
string agxPluginPath,
FileInfo targetExecutableFileInfo,
string targetDataPath )
{
// Some versions of Unity 2019.3 (fixed in 2019.3.9) isn't consistent
// where native modules are located. E.g., if Burst is installed, some
// dll's will be created in <project>_Data/Plugins/x86_64 and if AGX
// dll's are in <project>_Data/Plugins, the dll's wont load.
// - Unity 2019.3 and later: <project>_Data/Plugins/x86_64
// - Unity 2019.2 and earlier: <project>_Data/Plugins
if ( !Directory.Exists( AGXUnity.IO.Environment.GetPlayerPluginPath( targetDataPath ) ) )
Directory.CreateDirectory( AGXUnity.IO.Environment.GetPlayerPluginPath( targetDataPath ) );
// replaceduming all dlls are present in the plugins directory and that
// "Components" are in a folder named "agx" in the plugins directory.
// Unity will copy the dlls.
var sourceDirectory = new DirectoryInfo( IO.Utils.AGXUnityPluginDirectoryFull + Path.DirectorySeparatorChar + "agx" );
var destinationDirectory = new DirectoryInfo( AGXUnity.IO.Environment.GetPlayerAGXRuntimePath( targetDataPath ) );
Debug.Log( GUI.AddColorTag( "Copying AGX runtime data from: " +
IO.Utils.AGXUnityPluginDirectory +
Path.DirectorySeparatorChar +
"agx" +
" to " +
destinationDirectory.FullName, Color.green ) );
CopyDirectory( sourceDirectory, destinationDirectory );
// Deleting all .meta-files that are present in our "agx" folder.
foreach ( var fi in destinationDirectory.EnumerateFiles( "*.meta", SearchOption.AllDirectories ) )
fi.Delete();
VerifyBuild( targetDataPath );
CheckGenerateEncryptedRuntime( targetExecutableFileInfo );
}
19
View Source File : BuildProcessCallbacksHandler.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
private static void PostBuildExternal( string agxDynamicsPath,
string agxPluginPath,
FileInfo targetExecutableFileInfo,
string targetDataPath )
{
// Finding loaded modules/binaries in current process located
// in current environment AGX Dynamics directory. Additional
// modules/binaries that are optional, i.e., possibly located
// in another directory, are also included here.
var loadedAgxModulesPaths = new List<string>();
using ( new DynamicallyLoadedDependencies() ) {
var process = Process.GetCurrentProcess();
foreach ( ProcessModule module in process.Modules ) {
if ( module.FileName.IndexOf( "[In Memory]" ) >= 0 )
continue;
var isMatch = module.FileName.IndexOf( agxDynamicsPath ) == 0 ||
IsOutOfInstallDependency( module.FileName );
if ( isMatch )
loadedAgxModulesPaths.Add( module.FileName );
}
}
// Finding additional modules/binaries which an AGX Dynamics
// runtime may depend on, e.g., vcruntimeIII.dll and msvcpIII.dll.
var agxDepDir = AGXUnity.IO.Environment.Get( AGXUnity.IO.Environment.Variable.AGX_DEPENDENCIES_DIR );
if ( !string.IsNullOrEmpty( agxDepDir ) ) {
var agxDepDirInfo = new DirectoryInfo( agxDepDir );
foreach ( var file in agxDepDirInfo.EnumerateFiles( "*.dll", SearchOption.AllDirectories ) ) {
foreach ( var dependency in m_additionalDependencies )
if ( System.Text.RegularExpressions.Regex.IsMatch( file.Name, dependency ) )
loadedAgxModulesPaths.Add( file.FullName );
}
}
if ( loadedAgxModulesPaths.Count == 0 ) {
Debug.LogWarning( GUI.AddColorTag( "Copy AGX Dynamics binaries - no binaries found in current process.", Color.red ) );
return;
}
// dllTargetPath: ./<name>_Data/Plugins
var dllTargetPath = AGXUnity.IO.Environment.GetPlayerPluginPath( targetDataPath );
if ( !Directory.Exists( dllTargetPath ) )
Directory.CreateDirectory( dllTargetPath );
// agxRuntimeDataPath: ./<name>_Data/Plugins/agx
var agxRuntimeDataPath = AGXUnity.IO.Environment.GetPlayerAGXRuntimePath( targetDataPath );
if ( !Directory.Exists( agxRuntimeDataPath ) )
Directory.CreateDirectory( agxRuntimeDataPath );
Debug.Log( "Copying Components to: " + GUI.AddColorTag( agxRuntimeDataPath + Path.DirectorySeparatorChar + "Components", Color.green ) );
CopyDirectory( new DirectoryInfo( agxPluginPath + Path.DirectorySeparatorChar + "Components" ),
new DirectoryInfo( agxRuntimeDataPath + Path.DirectorySeparatorChar + "Components" ) );
var targetDataDir = agxRuntimeDataPath + Path.DirectorySeparatorChar + "data";
Debug.Log( "Copying data to: " + GUI.AddColorTag( targetDataDir, Color.green ) );
if ( !Directory.Exists( targetDataDir ) )
Directory.CreateDirectory( targetDataDir );
CopyDirectory( new DirectoryInfo( agxDynamicsPath + Path.DirectorySeparatorChar + "data" + Path.DirectorySeparatorChar + "TerrainMaterials" ),
new DirectoryInfo( targetDataDir + Path.DirectorySeparatorChar + "TerrainMaterials" ) );
foreach ( var modulePath in loadedAgxModulesPaths ) {
var moduleFileInfo = new FileInfo( modulePath );
try {
moduleFileInfo.CopyTo( dllTargetPath + Path.DirectorySeparatorChar + moduleFileInfo.Name, true );
string additionalInfo = "";
if ( IsOutOfInstallDependency( modulePath ) )
additionalInfo = GUI.AddColorTag( $" ({modulePath})", Color.yellow );
Debug.Log( "Successfully copied: " +
GUI.AddColorTag( dllTargetPath + Path.DirectorySeparatorChar, Color.green ) +
GUI.AddColorTag( moduleFileInfo.Name, Color.Lerp( Color.blue, Color.white, 0.75f ) ) +
additionalInfo );
}
catch ( Exception e ) {
Debug.Log( "Failed copying: " +
GUI.AddColorTag( dllTargetPath + Path.DirectorySeparatorChar, Color.red ) +
GUI.AddColorTag( moduleFileInfo.Name, Color.red ) +
": " + e.Message );
}
}
CheckGenerateEncryptedRuntime( targetExecutableFileInfo );
}
19
View Source File : Manager.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
private static void CreateDefaultreplacedets()
{
// Generate/synchronize custom editors.
if ( !Directory.Exists( Utils.CustomEditorGenerator.Path ) )
Directory.CreateDirectory( Utils.CustomEditorGenerator.Path );
Utils.CustomEditorGenerator.Synchronize();
// Shape visual material.
GetOrCreateShapeVisualDefaultMaterial();
// Merge split thresholds.
if ( !replacedetDatabase.IsValidFolder( IO.Utils.AGXUnityResourceDirectory + '/' + AGXUnity.MergeSplitThresholds.ResourceDirectory ) )
replacedetDatabase.CreateFolder( IO.Utils.AGXUnityResourceDirectory, AGXUnity.MergeSplitThresholds.ResourceDirectory );
GetOrCreatereplacedet<AGXUnity.GeometryContactMergeSplitThresholds>( IO.Utils.AGXUnityResourceDirectory + '/' + AGXUnity.GeometryContactMergeSplitThresholds.ResourcePath + ".replacedet" );
GetOrCreatereplacedet<AGXUnity.ConstraintMergeSplitThresholds>( IO.Utils.AGXUnityResourceDirectory + '/' + AGXUnity.ConstraintMergeSplitThresholds.ResourcePath + ".replacedet" );
}
19
View Source File : EditorUI.cs
License : MIT License
Project Creator : allenwp
License : MIT License
Project Creator : allenwp
static void SaveClearComponentGroup(EnreplacedyAdmin admin, ComponentGroup compGroup, bool save, bool clear)
{
List<Component> components = clear ? new List<Component>() : null;
var json = Serialization.SerializationHelper.Serialize(compGroup, components);
if (save)
{
Directory.CreateDirectory(ComponentGroup.ROOT_PATH);
FileLoader.SaveTextFile(compGroup.ComponentGroupPath, json);
}
if (clear)
{
foreach (var component in components)
{
admin.RemoveComponent(component);
}
}
}
19
View Source File : UploadTool.cs
License : MIT License
Project Creator : alonsoalon
License : MIT License
Project Creator : alonsoalon
public async Task<IResponseEnreplacedy<FileInfo>> UploadAvatarAsync(IFormFile file, CancellationToken cancellationToken = default)
{
var res = new ResponseEnreplacedy<FileInfo>();
var config = _systemConfig.CurrentValue.UploadAvatar;
if (file == null || file.Length < 1)
{
return res.Error("请上传文件!");
}
//格式限制
if (!config.ContentType.Contains(file.ContentType))
{
return res.Error("文件格式错误");
}
//大小限制
if (!(file.Length <= config.MaxSize))
{
return res.Error("文件过大");
}
var fileInfo = new File.FileInfo(file.FileName, file.Length);
fileInfo.UploadPath = config.UploadPath;
fileInfo.RequestPath = config.RequestPath;
fileInfo.RelativePath = _authUser.Tenant.Id;
fileInfo.SaveName = $"{_authUser.Id}.{fileInfo.Extension}";
if (!Directory.Exists(fileInfo.FileDirectory))
{
Directory.CreateDirectory(fileInfo.FileDirectory);
}
await SaveAsync(file, fileInfo.FilePath, cancellationToken);
return res.Ok(fileInfo);
}
19
View Source File : UploadTool.cs
License : MIT License
Project Creator : alonsoalon
License : MIT License
Project Creator : alonsoalon
public async Task<IResponseEnreplacedy<FileInfo>> UploadFileAsync(IFormFile file, FileUploadConfig config, object args, CancellationToken cancellationToken = default)
{
var res = new ResponseEnreplacedy<FileInfo>();
if (file == null || file.Length < 1)
{
return res.Error("请上传文件!");
}
//格式限制
if (!config.ContentType.Contains(file.ContentType))
{
return res.Error("文件格式错误");
}
//大小限制
if (!(file.Length <= config.MaxSize))
{
return res.Error("文件过大");
}
var fileInfo = new File.FileInfo(file.FileName, file.Length)
{
UploadPath = config.UploadPath,
RequestPath = config.RequestPath
};
var dateTimeFormat = config.DateTimeFormat.IsNotNull() ? DateTime.Now.ToString(config.DateTimeFormat) : "";
var format = config.Format.IsNotNull() ? StringHelper.Format(config.Format, args) : "";
fileInfo.RelativePath = Path.Combine(dateTimeFormat, format).ToPath();
if (!Directory.Exists(fileInfo.FileDirectory))
{
Directory.CreateDirectory(fileInfo.FileDirectory);
}
var dataCenterId = _systemConfig.CurrentValue?.DataCenterId ?? 5;
var workId = _systemConfig.CurrentValue?.WorkId ?? 20;
fileInfo.SaveName = $"{IdHelper.GenSnowflakeId(dataCenterId, workId)}.{fileInfo.Extension}";
await SaveAsync(file, fileInfo.FilePath, cancellationToken);
return res.Ok(fileInfo);
}
19
View Source File : UploadConfigExtensions.cs
License : MIT License
Project Creator : alonsoalon
License : MIT License
Project Creator : alonsoalon
private static void UseFileUploadConfig(IApplicationBuilder app, FileUploadConfig config)
{
if (!Directory.Exists(config.UploadPath))
{
Directory.CreateDirectory(config.UploadPath);
}
app.UseStaticFiles(new StaticFileOptions()
{
RequestPath = config.RequestPath,
FileProvider = new PhysicalFileProvider(config.UploadPath)
});
}
19
View Source File : ManualTestingController.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
private void CheckAndUpdateWorkflowFile(string org, string app)
{
string workflowFullFilePath = _serviceRepositorySettings.GetWorkflowPath(org, app, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)) + _serviceRepositorySettings.WorkflowFileName;
string templateWorkflowData = System.IO.File.ReadAllText(_generalSettings.WorkflowTemplate, Encoding.UTF8);
if (!System.IO.File.Exists(workflowFullFilePath))
{
// Create the workflow folder
Directory.CreateDirectory(_serviceRepositorySettings.GetWorkflowPath(org, app, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)));
System.IO.File.WriteAllText(workflowFullFilePath, templateWorkflowData, Encoding.UTF8);
}
else
{
if (ShouldUpdateFile(workflowFullFilePath, templateWorkflowData))
{
// Overwrite existing file
System.IO.File.WriteAllText(workflowFullFilePath, templateWorkflowData, Encoding.UTF8);
}
}
}
19
View Source File : AmazonAnnotationPackageProvider.cs
License : MIT License
Project Creator : AlturosDestinations
License : MIT License
Project Creator : AlturosDestinations
public async Task<AnnotationPackage> DownloadPackageAsync(AnnotationPackage package, CancellationToken token = default(CancellationToken))
{
this._packagesToDownload.Enqueue(package);
package.Enqueued = true;
while (this._packagesToDownload.Peek() != package)
{
await Task.Delay(1000).ConfigureAwait(false);
}
package.Enqueued = false;
this._downloadedPackage = package;
if (!Directory.Exists(this._config.ExtractionFolder))
{
Directory.CreateDirectory(this._config.ExtractionFolder);
}
var packagePath = Path.Combine(this._config.ExtractionFolder, package.PackageName);
var tempPath = $"{packagePath}_temp";
if (Directory.Exists(packagePath))
{
Directory.Delete(packagePath, true);
}
var files = await this._s3Client.ListObjectsV2Async(new ListObjectsV2Request
{
BucketName = this._config.BucketName,
Prefix = package.PackageName
});
var request = new TransferUtilityDownloadDirectoryRequest
{
BucketName = this._config.BucketName,
S3Directory = package.PackageName,
LocalDirectory = tempPath
};
request.DownloadedDirectoryProgressEvent += this.DownloadedDirectoryProgressEvent;
try
{
using (var fileTransferUtility = new TransferUtility(this._s3Client))
{
await fileTransferUtility.DownloadDirectoryAsync(request, token).ConfigureAwait(false);
}
}
finally
{
request.DownloadedDirectoryProgressEvent -= this.DownloadedDirectoryProgressEvent;
package.Downloading = false;
}
if (Directory.Exists(tempPath))
{
Directory.Move(tempPath, packagePath);
}
package.AvailableLocally = true;
var path = Path.Combine(this._config.ExtractionFolder, package.PackageName);
package.PrepareImages(path);
this._packagesToDownload.Dequeue();
return package;
}
19
View Source File : AmazonAnnotationPackageProvider.cs
License : MIT License
Project Creator : AlturosDestinations
License : MIT License
Project Creator : AlturosDestinations
private async Task UploadPackageAsync(string packagePath, List<string> tags, string user, CancellationToken token)
{
var packageName = Path.GetFileName(packagePath);
await this.AddPackageAsync(new AnnotationPackage
{
ExternalId = packageName,
User = user,
PackageName = packageName,
IsAnnotated = false,
AnnotationPercentage = 0,
Images = new List<AnnotationImage>(),
Tags = tags
}, token).ConfigureAwait(false);
var imageFiles = PackageHelper.GetImages(packagePath);
foreach (var file in imageFiles)
{
await this.UploadFileAsync(file, token).ConfigureAwait(false);
}
// Create local directory
if (!Directory.Exists(this._config.ExtractionFolder))
{
Directory.CreateDirectory(this._config.ExtractionFolder);
}
var localPackagePath = Path.Combine(this._config.ExtractionFolder, Path.GetFileName(packagePath));
if (Directory.Exists(localPackagePath))
{
Directory.Delete(localPackagePath, true);
}
Directory.CreateDirectory(localPackagePath);
foreach (var file in imageFiles)
{
File.Copy(file, Path.Combine(localPackagePath, Path.GetFileName(file)));
}
}
19
View Source File : JoplinExportService.cs
License : GNU General Public License v3.0
Project Creator : alxnbl
License : GNU General Public License v3.0
Project Creator : alxnbl
public void ExportNotebook(Notebook notebook, string sectionNameFilter = "", string pageNameFilter = "")
{
if (Directory.Exists(notebook.GetPath()))
Directory.Delete(notebook.GetPath(), true);
Directory.CreateDirectory(notebook.replacedle);
if (Directory.Exists("tmp"))
Directory.Delete("tmp", true);
Directory.CreateDirectory("tmp");
try
{
_oneNoteApp.FillNodebookTree(notebook);
}
catch (Exception ex)
{
Log.Error(ex, Localizer.GetString("ErrorDuringNotebookProcessingNbTree"), notebook.replacedle, notebook.Id, ex.Message);
return;
}
var sections = notebook.GetSections(true).Where(s => string.IsNullOrEmpty(sectionNameFilter) || s.replacedle == sectionNameFilter).ToList();
Log.Information($"--> Found {sections.Count} sections and sections groups\n");
// Create mdfile of notebook
ExportSection(notebook);
int cmpt = 0;
foreach (var section in sections)
{
cmpt++;
Log.Information($"Start processing section ({cmpt}/{sections.Count()}) : {section.GetPath()}\\{section.replacedle}");
ExportSection(section, pageNameFilter);
}
}
19
View Source File : MdExportService.cs
License : GNU General Public License v3.0
Project Creator : alxnbl
License : GNU General Public License v3.0
Project Creator : alxnbl
private void ExportSection(Node section, string pageNameFilter="")
{
if (!(section is Section sectionNote) || sectionNote.IsSectionGroup)
throw new InvalidOperationException("Cannot call ExportSection on section group with MdExport");
var pages = _oneNoteApp.GetPages(sectionNote).Where(p => string.IsNullOrEmpty(pageNameFilter) || p.replacedle == pageNameFilter).ToList();
var resourceFolderPath = Path.Combine(section.GetNotebookPath(), "_resources");
Directory.CreateDirectory(resourceFolderPath);
int cmpt = 0;
foreach (Page page in pages)
{
try
{
Log.Information($" Page {++cmpt}/{pages.Count} : {page.replacedleWithPageLevelTabulation}");
Directory.CreateDirectory(page.GetPageFolderRelativePath());
var docxFilePath = page.GetPageFileRelativePath() + ".docx";
File.Delete(docxFilePath);
_oneNoteApp.Publish(page.OneNoteId, Path.GetFullPath(docxFilePath), PublishFormat.pfWord);
var mdFileContent = _convertServer.ConvertDocxToMd(page, docxFilePath, resourceFolderPath, section.GetLevel());
var mdFilePath = page.GetPageFileRelativePath() + ".md";
try
{
mdFileContent = _convertServer.ExtractImagesToResourceFolder(page, mdFileContent, resourceFolderPath, mdFilePath, false, _appSettings.PostProcessingMdImgRef);
}
catch (Exception ex)
{
if (_appSettings.Debug)
Log.Warning($"Page '{page.GetPageFileRelativePath()}': {Localizer.GetString("ErrorImageExtract")}");
else
Log.Warning(ex, $"Page '{page.GetPageFileRelativePath()}'.");
}
mdFileContent = _convertServer.PostConvertion(page, mdFileContent, resourceFolderPath, mdFilePath, false);
File.WriteAllText(mdFilePath, mdFileContent);
}
catch (Exception e)
{
Log.Error(Localizer.GetString("ErrorDuringPageProcessing"), page.replacedleWithPageLevelTabulation, page.Id, e.Message);
}
}
}
19
View Source File : LockFileTest.cs
License : MIT License
Project Creator : ancientproject
License : MIT License
Project Creator : ancientproject
[Test]
[Author("Yuuki Wesp", "[email protected]")]
[Description("ensure create lock file in virtual file system and replacedert exist file")]
public void CreateIndexFileTest()
{
var dirs = new List<string>();
var files = new List<string>();
var shims = new List<Shim>();
shims.Add(Shim
.Replace(() => Pose.Is.A<FileSystemInfo>().FullName)
.With((FileSystemInfo @this) => @this.ToString()));
shims.Add(Shim
.Replace(() => Directory.CreateDirectory(Pose.Is.A<string>()))
.With((string s) => dirs.Chain(s, (list, v) => list.Add(v)).Mutate(x => new DirectoryInfo(x)).Return()));
shims.Add(Shim
.Replace(() => File.WriteAllText(Pose.Is.A<string>(), Pose.Is.A<string>()))
.With((string path, string content) => files.Add(path)));
shims.Add(Shim
.Replace(() => Directory.Exists(Pose.Is.A<string>()))
.With((string s) => dirs.Contains(s)));
shims.Add(Shim
.Replace(() => Pose.Is.A<DirectoryInfo>().Exists)
.With((DirectoryInfo @this) => dirs.Contains(@this.ToString())));
shims.Add(Shim
.Replace(() => Pose.Is.A<FileInfo>().Exists)
.With((FileInfo @this) => files.Contains(@this.ToString())));
try
{
PoseContext.Isolate(() =>
{
Indexer.FromLocal();
}, shims.ToArray());
replacedert.AreEqual("./deps/.ancient.lock", files.First());
}
catch (Exception e)
{
replacedert.Inconclusive(e.Message);
}
}
19
View Source File : BuildSLNUtilities.cs
License : MIT License
Project Creator : anderm
License : MIT License
Project Creator : anderm
public static void PerformBuild(BuildInfo buildInfo)
{
BuildTargetGroup buildTargetGroup = GetGroup(buildInfo.BuildTarget);
string oldBuildSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup);
if (!string.IsNullOrEmpty(oldBuildSymbols))
{
if (buildInfo.HasConfigurationSymbol())
{
buildInfo.AppendSymbols(BuildInfo.RemoveConfigurationSymbols(oldBuildSymbols));
}
else
{
buildInfo.AppendSymbols(oldBuildSymbols.Split(';'));
}
}
if ((buildInfo.BuildOptions & BuildOptions.Development) == BuildOptions.Development)
{
if (!buildInfo.HasConfigurationSymbol())
{
buildInfo.AppendSymbols(BuildSymbolDebug);
}
}
if (buildInfo.HasAnySymbols(BuildSymbolDebug))
{
buildInfo.BuildOptions |= BuildOptions.Development | BuildOptions.AllowDebugging;
}
if (buildInfo.HasAnySymbols(BuildSymbolRelease))
{
//Unity automatically adds the DEBUG symbol if the BuildOptions.Development flag is
//specified. In order to have debug symbols and the RELEASE symbole we have to
//inject the symbol Unity relies on to enable the /debug+ flag of csc.exe which is "DEVELOPMENT_BUILD"
buildInfo.AppendSymbols("DEVELOPMENT_BUILD");
}
BuildTarget oldBuildTarget = EditorUserBuildSettings.activeBuildTarget;
BuildTargetGroup oldBuildTargetGroup = GetGroup(oldBuildTarget);
EditorUserBuildSettings.SwitchActiveBuildTarget(buildTargetGroup, buildInfo.BuildTarget);
WSASDK oldWSASDK = EditorUserBuildSettings.wsaSDK;
if (buildInfo.WSASdk.HasValue)
{
EditorUserBuildSettings.wsaSDK = buildInfo.WSASdk.Value;
}
WSAUWPBuildType? oldWSAUWPBuildType = null;
if (EditorUserBuildSettings.wsaSDK == WSASDK.UWP)
{
oldWSAUWPBuildType = EditorUserBuildSettings.wsaUWPBuildType;
if (buildInfo.WSAUWPBuildType.HasValue)
{
EditorUserBuildSettings.wsaUWPBuildType = buildInfo.WSAUWPBuildType.Value;
}
}
var oldWSAGenerateReferenceProjects = EditorUserBuildSettings.wsaGenerateReferenceProjects;
if (buildInfo.WSAGenerateReferenceProjects.HasValue)
{
EditorUserBuildSettings.wsaGenerateReferenceProjects = buildInfo.WSAGenerateReferenceProjects.Value;
}
var oldColorSpace = PlayerSettings.colorSpace;
if (buildInfo.ColorSpace.HasValue)
{
PlayerSettings.colorSpace = buildInfo.ColorSpace.Value;
}
if (buildInfo.BuildSymbols != null)
{
PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, buildInfo.BuildSymbols);
}
string buildError = "Error";
try
{
if (EditorUserBuildSettings.wsaSDK == WSASDK.UWP)
{
VerifyWsaUwpSdkIsInstalled(EditorUserBuildSettings.wsaUWPSDK);
}
// For the WSA player, Unity builds into a target directory.
// For other players, the OutputPath parameter indicates the
// path to the target executable to build.
if (buildInfo.BuildTarget == BuildTarget.WSAPlayer)
{
Directory.CreateDirectory(buildInfo.OutputDirectory);
}
OnPreProcessBuild(buildInfo);
buildError = BuildPipeline.BuildPlayer(
buildInfo.Scenes.ToArray(),
buildInfo.OutputDirectory,
buildInfo.BuildTarget,
buildInfo.BuildOptions);
if (buildError.StartsWith("Error"))
{
throw new Exception(buildError);
}
}
finally
{
OnPostProcessBuild(buildInfo, buildError);
if (buildInfo.BuildTarget == BuildTarget.WSAPlayer && EditorUserBuildSettings.wsaGenerateReferenceProjects)
{
UwpProjectPostProcess.Execute(buildInfo.OutputDirectory);
}
PlayerSettings.colorSpace = oldColorSpace;
PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, oldBuildSymbols);
if (oldWSAUWPBuildType.HasValue)
{
EditorUserBuildSettings.wsaUWPBuildType = oldWSAUWPBuildType.Value;
}
EditorUserBuildSettings.wsaSDK = oldWSASDK;
EditorUserBuildSettings.wsaGenerateReferenceProjects = oldWSAGenerateReferenceProjects;
EditorUserBuildSettings.SwitchActiveBuildTarget(oldBuildTargetGroup, oldBuildTarget);
}
}
19
View Source File : CSharpProjectWriter.cs
License : MIT License
Project Creator : AndresTraks
License : MIT License
Project Creator : AndresTraks
private void WriteItem(SourceItemDefinition item)
{
if (item is FolderDefinition folder)
{
Directory.CreateDirectory(folder.FullPath);
}
if (item is RootFolderDefinition rootFolder)
{
Directory.CreateDirectory(rootFolder.FullPath);
}
if (item is HeaderDefinition header)
{
WriteHeader(header);
}
foreach (SourceItemDefinition child in item.Children)
{
WriteItem(child);
}
}
19
View Source File : util.cs
License : GNU Lesser General Public License v3.0
Project Creator : angturil
License : GNU Lesser General Public License v3.0
Project Creator : angturil
public static string Backup()
{
DateTime Now = DateTime.Now;
string BackupName = Path.Combine(RequestBotConfig.Instance.backuppath, $"SRMBACKUP-{Now.ToString("yyyy-MM-dd-HHmm")}.zip");
Plugin.Log($"Backing up {Plugin.DataPath}");
try
{
if (!Directory.Exists(RequestBotConfig.Instance.backuppath))
Directory.CreateDirectory(RequestBotConfig.Instance.backuppath);
ZipFile.CreateFromDirectory(Plugin.DataPath, BackupName, System.IO.Compression.CompressionLevel.Fastest, true);
RequestBotConfig.Instance.LastBackup = DateTime.Now.ToString();
RequestBotConfig.Instance.Save();
Plugin.Log($"Backup success writing {BackupName}");
return success;
}
catch
{
}
Plugin.Log($"Backup failed writing {BackupName}");
return $"Failed to backup to {BackupName}";
}
19
View Source File : GeneralPreference.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
private static GeneralPreference CreateDefaultPreference()
{
if (!Directory.Exists(Locations.APP_USER_FOLDER))
Directory.CreateDirectory(Locations.APP_USER_FOLDER);
userPrefDatabase = new Database(USER_PREF_FILE_PATH);
var UserPrefs = GetDefaultPreference();
userPrefDatabase.CreateTable<GeneralPreference>();
userPrefDatabase.Insert(UserPrefs);
return UserPrefs;
}
See More Examples