public void CreateDatabase(string path) { //The file that was just created does not have a schema, so SQLite won't touch it. //The file must have a schema or not exist for use with SQLite, so we'll delete //it and install a schema try { FileEx.SafeDelete(path); } catch (IOException x) { MessageDlg.ShowException(this, x); return; } //Create file, initialize db try { IonMobilityDb.CreateIonMobilityDb(path); textDatabase.Text = path; } catch (DatabaseOpeningException x) { MessageDlg.ShowException(this, x); } catch (Exception x) { var message = TextUtil.LineSeparate(string.Format(Resources.EditIonMobilityLibraryDlg_CreateDatabase_The_ion_mobility_library_file__0__could_not_be_created, path), x.Message); MessageDlg.ShowWithException(this, message, x); } }
public void ReadOnly() { var root = Path.GetFullPath("DirectoryMarkdownProcessor/Readonly"); try { DirectoryMarkdownProcessor processor = new( root, writeHeader : false, readOnly : true, newLine : "\r", directoryIncludes : _ => true, markdownDirectoryIncludes : _ => true, snippetDirectoryIncludes : _ => true); processor.AddSnippets( SnippetBuild("snippet1"), SnippetBuild("snippet2") ); processor.Run(); FileInfo fileInfo = new(Path.Combine(root, "one.md")); Assert.True(fileInfo.IsReadOnly); } finally { foreach (var file in Directory.EnumerateFiles(root)) { FileEx.ClearReadOnly(file); } } }
private string SelectImageFile(string parnFnOld = null) { string imageName = null; try { imageName = OpenFileDialogEx.GetOpenFileName("选择图片", "图片文件|*.gif;*.jpeg;*.jpg;*.png;*.tif;*.tiff", null); if (!string.IsNullOrEmpty(imageName)) { if (FileEx.IsFileLengthMoreKB(imageName, 1024)) { throw new Exception("图片大小不能超过1MB"); } BitmapImage bitmapImage; if (!BitmapImageEx.TryCreateFromFile(imageName, out bitmapImage)) { throw new Exception("无法解析图片,请选择正常的图片"); } imageName = ShortcutImageHelper.AddNewImage(imageName, parnFnOld); } } catch (Exception ex) { Log.Exception(ex); MsgBox.ShowErrTip(ex.Message, null); } return(imageName); }
/// <summary> /// Creates and returns an uninitialized <see cref="IPersistentData"/> instance. /// </summary> /// <param name="importedBuildPath">Optional path to a build file that should be imported.</param> public static IPersistentData CreatePersistentData(string importedBuildPath) { if (!File.Exists(FilePath)) { var deserializer = new PersistentDataDeserializerCurrent(); return(new PersistentData(deserializer, importedBuildPath)); } try { return(Deserialize(FilePath, importedBuildPath)); } catch (Exception ex) { if (File.Exists(BackupPath)) { return(Deserialize(BackupPath, importedBuildPath)); } var badFilePath = AppData.GetFolder(true) + FileName + "_Bad.xml"; File.Copy(FilePath, badFilePath, true); FileEx.DeleteIfExists(FilePath); FileEx.DeleteIfExists(BackupPath); Log.Error("Could not deserialize PeristentData file", ex); throw new Exception(ex.Message + "\nYour PersistentData file could not be loaded correctly. It has been moved to " + badFilePath); } }
public static bool ValidateLibraryPath(Control owner, string path) { if (!File.Exists(path)) { MessageDlg.Show(owner, string.Format(Resources.EditLibraryDlg_OkDialog_The_file__0__does_not_exist, path)); return(false); } if (FileEx.IsDirectory(path)) { MessageDlg.Show(owner, string.Format(Resources.EditLibraryDlg_OkDialog_The_path__0__is_a_directory, path)); return(false); } // Display an error message if the user is trying to add a BiblioSpec library, // and the library has the text "redundant" in the file name. if (path.EndsWith(BiblioSpecLiteSpec.EXT_REDUNDANT)) { var message = TextUtil.LineSeparate(string.Format(Resources.EditLibraryDlg_OkDialog_The_file__0__appears_to_be_a_redundant_library, path), Resources.EditLibraryDlg_OkDialog_Please_choose_a_non_redundant_library); MessageDlg.Show(owner, string.Format(message, path)); return(false); } return(true); }
public virtual void ReadModule() { tempAssembly = $"{AssemblyFilePath}.tmp"; File.Copy(AssemblyFilePath, tempAssembly, true); if (debugReaderProvider != null && DebugSymbols != DebugSymbolsType.Embedded) { var symbolsPath = pdbFound ? pdbPath : mdbPath; tempSymbols = $"{symbolsPath}.tmp"; if (File.Exists(symbolsPath)) { File.Copy(symbolsPath, tempSymbols, true); SymbolStream = FileEx.OpenRead(tempSymbols); } } var readerParameters = new ReaderParameters { AssemblyResolver = assemblyResolver, ReadSymbols = SymbolStream != null || DebugSymbols == DebugSymbolsType.Embedded, SymbolReaderProvider = debugReaderProvider, SymbolStream = SymbolStream, }; ModuleDefinition = ModuleDefinition.ReadModule(tempAssembly, readerParameters); }
private static void DeleteFiles(TestFilesDir testFilesDir, IEnumerable <string> fileNames) { foreach (var fileName in fileNames) { FileEx.SafeDelete(testFilesDir.GetTestPath(fileName)); } }
/// <summary> /// Retrieves a list of IP addresses by parsing a text file. /// </summary> /// <returns>List of IP addresses.</returns> public async Task <AddressModel> RetrieveIPAddressListFromFileAsync() { if (!File.Exists(s_inputFile)) { throw new FileNotFoundException(); } AddressModel addressList = new AddressModel() { Addresses = new List <string>() }; string[] fileAsLines = await FileEx.ReadAllLinesAsync(s_inputFile, Encoding.Default); if (fileAsLines != null && fileAsLines.Length > 0) { foreach (string address in fileAsLines) { if (IsAddressValid(address.Trim())) { addressList.Addresses.Add(address); } } } return(addressList); }
/// <summary> /// Reads the text content of a file and determines its Encoding. /// </summary> /// <param name="fileName"></param> /// <param name="ignoreInsignificantWhiteSpace"></param> /// <param name="progress"></param> /// <returns></returns> public static FileContentInfo GetXmlText(string fileName, bool ignoreInsignificantWhiteSpace, IDiffProgress progress) { var contentInfo = new FileContentInfo(); //// This should be created from in-memory text to save IO and support editing //// using (StreamReader reader = new StreamReader(fileName, Encoding.Default, true)) //// { //// contentInfo.Lines = GetXmlTextLines(reader, ignoreInsignificantWhiteSpace, progress); //// } // Read the RAW text content const int DefaultBufferSize = 4096; const FileOptions DefaultOptions = FileOptions.Asynchronous | FileOptions.SequentialScan; using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, DefaultOptions)) { var bom = new byte[4]; // Decode bom (if any) and continue to read text content stream.Read(bom, 0, 4); stream.Seek(0, SeekOrigin.Begin); contentInfo.TextEncoding = FileEx.GetEncoding(bom); using (StreamReader reader = new StreamReader(stream, contentInfo.TextEncoding)) { contentInfo.TextContent = reader.ReadToEnd(); } } return(contentInfo); }
private void BuildLibraryError(string inputFile, string libraryPath, params string[] messageParts) { string redundantBuildPath = TestFilesDir.GetTestPath(_libraryName + BiblioSpecLiteSpec.EXT_REDUNDANT); FileEx.SafeDelete(redundantBuildPath); string nonredundantBuildPath = TestFilesDir.GetTestPath(_libraryName + BiblioSpecLiteSpec.EXT); FileEx.SafeDelete(nonredundantBuildPath); ReportLibraryBuildFailures = false; BuildLibrary(TestFilesDir.GetTestPath("library_errors"), new[] { inputFile }, libraryPath, false, false, false, false, null); var messageDlg = WaitForOpenForm <MessageDlg>(); Assert.IsNotNull(messageDlg, "No message box shown"); AssertEx.Contains(messageDlg.Message, "ERROR"); if (messageParts.Length == 0) { AssertEx.Contains(messageDlg.Message, inputFile, "line"); } else { AssertEx.Contains(messageDlg.Message, messageParts); } OkDialog(messageDlg, messageDlg.OkDialog); CheckLibraryExistence(redundantBuildPath, false); CheckLibraryExistence(nonredundantBuildPath, false); WaitForConditionUI(() => !PeptideSettingsUI.IsBuildingLibrary); }
public void CreateDb(string fileName) { // If the file exists, then the user chose to overwrite, // so delete the existing file. try { FileEx.SafeDelete(fileName); } catch (IOException x) { MessageDlg.ShowException(this, x); return; } Settings.Default.ProteomeDbDirectory = Path.GetDirectoryName(fileName); try { ProteomeDb.CreateProteomeDb(fileName); } catch (Exception x) { var message = TextUtil.LineSeparate(string.Format( Resources .BuildBackgroundProteomeDlg_btnCreate_Click_An_error_occurred_attempting_to_create_the_proteome_file__0__, fileName), x.Message); MessageDlg.ShowWithException(this, message, x); } if (textName.Text.Length == 0) { textName.Text = Path.GetFileNameWithoutExtension(fileName); } textPath.Text = fileName; // This will cause RefreshStatus() }
private void DoTestImportSim(bool asSmallMolecules) { if (asSmallMolecules && !RunSmallMoleculeTestVersions) { System.Console.Write(MSG_SKIPPING_SMALLMOLECULE_TEST_VERSION); return; } var testFilesDir = new TestFilesDir(TestContext, ZIP_FILE); string docPath = testFilesDir.GetTestPath(DOCUMENT_NAME); string cachePath = ChromatogramCache.FinalPathForName(docPath, null); FileEx.SafeDelete(cachePath); SrmDocument doc = ResultsUtil.DeserializeDocument(docPath); var pepdoc = doc; if (asSmallMolecules) { var refine = new RefinementSettings(); doc = refine.ConvertToSmallMolecules(pepdoc, TestContext.ResultsDirectory); } using (var docContainer = new ResultsTestDocumentContainer(doc, docPath)) { // Import the mzML file and verify Mz range Import(docContainer, testFilesDir.GetTestPath(RESULTS_NAME), 510, 512); Import(docContainer, testFilesDir.GetTestPath(RESULTS_NAME2), 555, 557); } }
void init() { if (isFinishInited) { return; } isFinishInited = true; instance = target as MyUIPanel; string language = "Chinese"; if (!Localization.language.Equals(language)) { byte[] buff = null; string languageFile = PStr.b( CLPathCfg.self.localizationPath, language, ".txt").e(); #if UNITY_EDITOR if (CLCfgBase.self.isEditMode) { languageFile = PStr.b().a(CLPathCfg.persistentDataPath).a("/").a(languageFile).e(); languageFile = languageFile.Replace("/upgradeRes/", "/upgradeRes4Dev/"); buff = File.ReadAllBytes(languageFile); } else { buff = FileEx.readNewAllBytes(languageFile); } #else buff = FileEx.readNewAllBytes(languageFile); #endif Localization.Load(language, buff); } title = Localization.Get(instance.titleKeyName); }
public bool ReMuxToMkv(string inputName, MediaInfo keep, string outputName) { if (keep == null) { return(ReMuxToMkv(inputName, outputName)); } // Verify correct data type Debug.Assert(keep.Parser == ToolType.MkvMerge); // Delete output file FileEx.DeleteFile(outputName); // Create the track number filters // The track numbers are reported by MkvMerge --identify, use the track.id values string videoTracks = keep.Video.Count > 0 ? $"--video-tracks {string.Join(",", keep.Video.Select(info => info.Id.ToString(CultureInfo.InvariantCulture)))} " : "--no-video "; string audioTracks = keep.Audio.Count > 0 ? $"--audio-tracks {string.Join(",", keep.Audio.Select(info => info.Id.ToString(CultureInfo.InvariantCulture)))} " : "--no-audio "; string subtitleTracks = keep.Subtitle.Count > 0 ? $"--subtitle-tracks {string.Join(",", keep.Subtitle.Select(info => info.Id.ToString(CultureInfo.InvariantCulture)))} " : "--no-subtitles "; // Remux tracks string snippets = Program.Options.TestSnippets ? Snippet : ""; string commandline = $"{MergeOptions} {snippets} --output \"{outputName}\" {videoTracks}{audioTracks}{subtitleTracks} \"{inputName}\""; int exitCode = Command(commandline); return(exitCode is 0 or 1); }
private static void Update(string updateeFilePath, string packageContentDirPath, bool restartUpdatee) { // Wait until updatee is writable to ensure all running instances have exited WriteLog("Waiting for all running updatee instances to exit..."); while (!FileEx.CheckWriteAccess(updateeFilePath)) { Thread.Sleep(100); } // Copy over the package contents WriteLog("Copying package contents from storage to updatee's directory..."); var updateeDirPath = Path.GetDirectoryName(updateeFilePath); DirectoryEx.Copy(packageContentDirPath, updateeDirPath); // Launch the updatee again if requested if (restartUpdatee) { WriteLog("Restarting updatee..."); using (var restartedUpdateeProcess = Process.Start(updateeFilePath)) WriteLog($"Restarted as pid:{restartedUpdateeProcess?.Id}."); } // Delete package content directory WriteLog("Deleting package contents from storage..."); Directory.Delete(packageContentDirPath, true); }
private NativeData CheckSuperMemoExecutable() { var nativeDataCfg = LoadNativeDataConfig(); var smFile = new FilePath(StartupConfig.SMBinPath); if (smFile.Exists() == false) { throw new SMAException( $"Invalid file path for sm executable file: '{StartupConfig.SMBinPath}' could not be found. SMA cannot continue."); } if (smFile.HasPermission(FileIOPermissionAccess.Read) == false) { throw new SMAException($"SMA needs read access to execute SM executable at {smFile.FullPath}."); } if (smFile.IsLocked()) { throw new SMAException($"{smFile.FullPath} is locked. Make sure it isn't already running."); } var smFileCrc32 = FileEx.GetCrc32(smFile.FullPath); var nativeData = nativeDataCfg.SafeGet(smFileCrc32.ToUpper(CultureInfo.InvariantCulture)); if (nativeData == null) { throw new SMAException($"Unknown SM executable version with crc32 {smFileCrc32}."); } LogTo.Information($"SuperMemo version {nativeData.SMVersion} detected"); return(nativeData); }
public static byte[] CombineFiles(FileEx[] data) { List<byte> result = new List<byte>(); // Generating the header int pos = 0; string toAdd = ""; foreach(var file in data) { int future = pos + file.data.Length; toAdd += string.Format("[|{0}|{1}|{2}|]", file.name, pos, file.data.Length); pos = future; } result.AddRange(GetBytes(toAdd)); //Adding the header's size result.InsertRange(0, BitConverter.GetBytes(result.Count)); //Adding the file data foreach(var file in data) { result.AddRange(file.data); } return result.ToArray(); }
public override bool Update(string updateFile) { // TODO: This only works for Windows // FfMpeg archives have versioned folders in the zip file // The 7Zip -spe option does not work for zip files // https://sourceforge.net/p/sevenzip/discussion/45798/thread/8cb61347/ // We need to extract to the root tools folder, that will create a subdir, then rename to the destination folder string extractPath = Tools.GetToolsRoot(); // Extract the update file Log.Logger.Information("Extracting {UpdateFile} ...", updateFile); if (!Tools.SevenZip.UnZip(updateFile, extractPath)) { return(false); } // Delete the tool destination directory string toolPath = GetToolFolder(); if (!FileEx.DeleteDirectory(toolPath, true)) { return(false); } // Build the versioned out folder from the downloaded filename // E.g. ffmpeg-3.4-win64-static.zip to .\Tools\FFmpeg\ffmpeg-3.4-win64-static extractPath = Tools.CombineToolPath(Path.GetFileNameWithoutExtension(updateFile)); // Rename the extract folder to the tool folder // E.g. ffmpeg-3.4-win64-static to .\Tools\FFMpeg return(FileEx.RenameFolder(extractPath, toolPath)); }
private bool ConvertToMkv(string inputName, string videoCodec, int videoQuality, string audioCodec, MediaInfo keep, MediaInfo reEncode, string outputName) { // Simple encoding of audio and video and passthrough of other tracks if (keep == null || reEncode == null) { return(ConvertToMkv(inputName, videoCodec, videoQuality, audioCodec, outputName)); } // Delete output file FileEx.DeleteFile(outputName); // Create an input and output map CreateFfMpegMap(videoCodec, videoQuality, audioCodec, keep, reEncode, out string input, out string output); // TODO: Error with some PGS subtitles // https://trac.ffmpeg.org/ticket/2622 // [matroska,webm @ 000001d77fb61ca0] Could not find codec parameters for stream 2 (Subtitle: hdmv_pgs_subtitle): unspecified size // Consider increasing the value for the 'analyzeduration' and 'probesize' options // Convert using map string snippet = Program.Options.TestSnippets ? Snippet : ""; string commandline = $"{GlobalOptions} -i \"{inputName}\" {OutputOptions} {snippet} {input} {output} -f matroska \"{outputName}\""; int exitCode = Command(commandline); return(exitCode == 0); }
Result AddItem(HttpResponseMessage response, Uri uri, CancellationToken token) { var timestamp = Timestamp.FromResponse(uri, response); #if NET5_0 var meta = MetaData.FromEnumerables(response.Headers, response.Content.Headers, response.TrailingHeaders); #else var meta = MetaData.FromEnumerables(response.Headers, response.Content.Headers); #endif var tempFile = FilePair.GetTemp(); try { using var httpStream = response.Content.ReadAsStream(token); using (var contentFileStream = FileEx.OpenWrite(tempFile.Content)) using (var metaFileStream = FileEx.OpenWrite(tempFile.Meta)) using (var writer = new Utf8JsonWriter(metaFileStream)) { JsonSerializer.Serialize(writer, meta); httpStream.CopyTo(contentFileStream); } return(BuildResult(timestamp, tempFile)); } finally { tempFile.Delete(); } }
/// <summary> /// Import builds from legacy build save file "savedBuilds" to PersistentData.xml. /// Warning: This will remove the "savedBuilds" /// </summary> private async Task ImportLegacySavedBuildsAsync() { if (!File.Exists("savedBuilds")) { return; } try { var text = await FileEx.ReadAllTextAsync("savedBuilds"); foreach (var b in text.Split('\n')) { var build = new PoEBuild { Name = b.Split(';')[0].Split('|')[0] }; if (HasBuildNote(b)) { build.TreeUrl = b.Split(';')[1].Split('|')[0]; build.Note = b.Split(';')[1].Split('|')[1]; } else { build.TreeUrl = b.Split(';')[1]; } PersistentData.RootBuild.Builds.Add(build); } File.Move("savedBuilds", "savedBuilds.old"); } catch (Exception e) { Log.Error("Could not load legacy savedBuilds file", e); } }
public BiblioSpecLiteBuilder GetLibBuilder(SrmDocument doc, string docFilePath, bool includeAmbiguousMatches) { string outputPath = BiblioSpecLiteSpec.GetLibraryFileName(docFilePath); // Check to see if the library is already there, and if it is, // "Append" instead of "Create" bool libraryExists = File.Exists(outputPath); var libraryBuildAction = LibraryBuildAction.Create; if (libraryExists) { if (doc.Settings.HasDocumentLibrary) { libraryBuildAction = LibraryBuildAction.Append; } else { // If the document does not have a document library, then delete the one that we have found // CONSIDER: it may be that user is trying to re-import, in which case this file is probably in use FileEx.SafeDelete(outputPath); FileEx.SafeDelete(Path.ChangeExtension(outputPath, BiblioSpecLiteSpec.EXT_REDUNDANT)); } } string name = Path.GetFileNameWithoutExtension(docFilePath); return(new BiblioSpecLiteBuilder(name, outputPath, SearchFilenames) { Action = libraryBuildAction, KeepRedundant = true, CutOffScore = CutoffScore, Id = Helpers.MakeId(name), IncludeAmbiguousMatches = includeAmbiguousMatches }); }
async Task <Result> InnerAddItemAsync( CancellationToken token, Func <CancellationToken, Task <Stream> > httpContentFunc, MetaData meta, Timestamp timestamp) { var tempFile = FilePair.GetTemp(); try { #if NET5_0 await using var httpStream = await httpContentFunc(token); await using (var contentFileStream = FileEx.OpenWrite(tempFile.Content)) await using (var metaFileStream = FileEx.OpenWrite(tempFile.Meta)) { #else using var httpStream = await httpContentFunc(token); using (var contentFileStream = FileEx.OpenWrite(tempFile.Content)) using (var metaFileStream = FileEx.OpenWrite(tempFile.Meta)) { #endif await JsonSerializer.SerializeAsync(metaFileStream, meta, cancellationToken : token); await httpStream.CopyToAsync(contentFileStream, token); } return(BuildResult(timestamp, tempFile)); } finally { tempFile.Delete(); } }
public void WatersLockmassCmdlinePerfTest() { if (IsPerfTest && !RunPerfTests) { return; // Don't want to run this lengthy test right now } TestFilesZip = "https://skyline.gs.washington.edu/perftests/PerfTestLockmass.zip"; TestFilesPersistent = new[] { "ID19638_01_UCA195_2533_082715.raw" }; // List of files that we'd like to unzip alongside parent zipFile, and (re)use in place TestFilesDir = new TestFilesDir(TestContext, TestFilesZip, "CmdlineTest", TestFilesPersistent); var skyfile = GetTestPath("2533_FattyAcids.sky"); var rawPath = GetTestPath(TestFilesPersistent[0]); const double lockmassNegative = 554.2615; // Exercise the commandline var outPathUncorrected = TestFilesDir.GetTestPath("cmdlineTestUncorrected.sky"); var outPathCorrected = TestFilesDir.GetTestPath("cmdlineTestCorrected.sky"); RunCommand("--in=" + skyfile, "--import-file=" + rawPath, "--out=" + outPathUncorrected); FileEx.SafeDelete(Path.ChangeExtension(skyfile, ChromatogramCache.EXT)); var cmdDocUncorrected = ResultsUtil.DeserializeDocument(outPathUncorrected); RunCommand("--in=" + skyfile, "--import-file=" + rawPath, "--import-lockmass-negative=" + lockmassNegative, "--out=" + outPathCorrected); var cmdDocCorrected = ResultsUtil.DeserializeDocument(outPathCorrected); ComparePeaks(cmdDocCorrected, cmdDocUncorrected); }
public override bool Update(string updateFile) { // We need to keep the previous copy of 7zip so we can extract the new copy // We need to extract to a temp location in the root tools folder, then rename to the destination folder // Build the versioned folder from the downloaded filename // E.g. 7z1805-extra.7z to .\Tools\7z1805-extra string extractPath = Tools.CombineToolPath(Path.GetFileNameWithoutExtension(updateFile)); // Extract the update file Log.Logger.Information("Extracting {UpdateFile} ...", updateFile); if (!Tools.SevenZip.UnZip(updateFile, extractPath)) { return(false); } // Delete the tool destination directory string toolPath = GetToolFolder(); if (!FileEx.DeleteDirectory(toolPath, true)) { return(false); } // Rename the folder // E.g. 7z1805-extra to .\Tools\7Zip return(FileEx.RenameFolder(extractPath, toolPath)); }
public OpenFolderAction(string path, IFileExplorer fileExplorer) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException(nameof(path)); } if (fileExplorer == null) { throw new ArgumentNullException(nameof(fileExplorer)); } _fileExplorer = fileExplorer; _task = Task.Run(() => { if (!FileEx.Exists(path, TimeSpan.FromSeconds(1))) { FullFoldername = FileEx.FindClosestExistingFolder(path); _fileExplorer.OpenFolder(FullFoldername); } else { FullFoldername = path; _fileExplorer.SelectFile(path); } }) .ContinueWith(OnFolderOpened); }
public OpenFolderAction(string[] files, string folder, IFileExplorer fileExplorer) { if (files == null) { throw new ArgumentNullException(nameof(files)); } if (string.IsNullOrEmpty(folder)) { throw new ArgumentNullException(nameof(folder)); } if (fileExplorer == null) { throw new ArgumentNullException(nameof(fileExplorer)); } _fileExplorer = fileExplorer; _task = Task.Run(() => { if (!Directory.Exists(folder)) { FullFoldername = FileEx.FindClosestExistingFolder(folder); _fileExplorer.OpenFolder(FullFoldername); } else { FullFoldername = folder; _fileExplorer.SelectFiles(FullFoldername, files); } }) .ContinueWith(OnFolderOpened); }
public void Confirm() { var format = SelectedDownloadOption.Format; // Prompt user for output file path var filter = $"{format.ToUpperInvariant()} file|*.{format}"; var defaultFileName = $"{Video.GetFileNameSafeTitle()}.{format}"; var filePath = _dialogManager.PromptSaveFilePath(filter, defaultFileName); // If canceled - return if (filePath.IsNullOrWhiteSpace()) { return; } // Save last used format _settingsService.LastFormat = format; // Create download view model var download = _viewModelFactory.CreateDownloadViewModel(Video, filePath, format, SelectedDownloadOption); // Create empty file to "lock in" the file path FileEx.CreateEmptyFile(filePath); // Close dialog Close(download); }
private async Task LoadAsync(string name, string path, IDataLoader dataLoader) { Log.InfoFormat("Loading {0} ...", name); var fullPath = Path.Combine(_savePath, path); if (path.Any()) { var isFolder = dataLoader.SavePathIsFolder; var tmpPath = fullPath + (isFolder ? "Tmp" : ".tmp"); if (isFolder) { Directory.CreateDirectory(tmpPath); } await dataLoader.LoadAndSaveAsync(_httpClient, tmpPath); if (isFolder) { DirectoryEx.MoveOverwriting(tmpPath, fullPath); } else { FileEx.MoveOverwriting(tmpPath, fullPath); } } else { // This is for SkillTreeLoader which writes to multiple files/folders and does the tmp stuff itself await dataLoader.LoadAndSaveAsync(_httpClient, fullPath); } Log.InfoFormat("Loaded {0}!", name); }
public void Initialize() { string asmDir = PathEx.GetDirectoryName(typeof(GitTests).Assembly.Location); this.rootDir = PathEx.Combine(asmDir, "test-root"); DirectoryEx.Create(this.rootDir); DirectoryEx.Clear(this.rootDir); if (FileEx.Exists(credentialsFilePath)) { var lines = File.ReadAllLines(credentialsFilePath); this.userName = lines[0]; this.password = SecureStringExtensions.ToSecureString(lines[1]); } var fileOps = new TestFileOperationsExecuter(Path.Combine(this.rootDir, "agent")); //var fileOps = new SimulatedFileOperationsExecuter(fileOps); //fileOps.MessageLogged += (s, e) => TestLogger.Instance.Log(e.Level, e.Message); this.fileOps = fileOps; this.processExecuter = new TestRemoteProcessExecuter(); this.jobExecuter = new TestRemoteJobExecuter(); }
static void GenerateMessageFromProto() { string dir = Application.dataPath + "/../../public/proto/"; string[] protos = Directory.GetFiles(dir, "*.proto"); string codeID = ""; int id = MESSAGEID_BEGIN; for (int i = 0; i < protos.Length; ++i) { string[] lines = File.ReadAllLines(protos[i]); for (int j = 0; j < lines.Length; ++j) { if (lines[j].Contains("message") == false) { continue; } string classname = lines[j].Replace("message", "").Trim(); if (IsMessage(classname)) { string ID = GetID(classname); codeID += "\t" + ID + " = " + (id++) + ",\n"; WriteFile(classname, ID); } } } FileEx.ReplaceContent(Application.dataPath + "/Scripts/Message/MessageID.cs", "//MESSAGEID_BEGIN", "//MESSAGEID_END", codeID); }
public static FileEx[] SplitFiles(byte[] data) { List<FileEx> result = new List<FileEx>(); // Get the header size int headerSize = BitConverter.ToInt32(data,0); // Get the header byte[] header = new byte[headerSize]; Buffer.BlockCopy(data, 4, header, 0, headerSize); string headerText = GetString(header); // The offset from where the bytes of the first file will start int initialOffset = headerSize + 4; // For each file create a new fileex item and add it to the result foreach (Match match in Regex.Matches(headerText, @"(\[\|)(.*?)(\|\])")) { var matches = Regex.Matches(match.Value, @"(?<=\|)(.*?)(?=\|)"); FileEx item = new FileEx(); int start=0, len=0; for(int i = 0;i<3;i++) { string val = matches[i].Value; switch(i) { case 0: item.name = val; break; case 1: start = int.Parse(val); break; case 2: len = int.Parse(val); break; } } item.data = new byte[len]; Buffer.BlockCopy(data, initialOffset + start, item.data, 0, len); result.Add(item); } return result.ToArray(); }