void OnValidate() { if (!import) { return; } import = false; var liveRemotePath = RemotePath + @"\lives\" + liveName; var liveLocalPath = LocalPath + @"\lives\" + liveName + ".json"; string liveJson = File.ReadAllText(liveRemotePath); Debug.Log(liveJson); File.WriteAllText(liveLocalPath, liveJson); var live = JsonUtility.FromJson <ApiLiveResponse>(liveJson).content; Debug.Log(live.live_name); var mapRemotePath = RemotePath + @"\maps\" + live.map_path; var mapLocalPath = LocalPath + @"\maps\" + live.map_path; string mapJson = ApiLiveMap.Transform(File.ReadAllText(mapRemotePath)); File.WriteAllText(mapLocalPath, mapJson); var bgmRemotePath = RemotePath + @"\bgms\" + live.bgm_path; var bgmLocalPath = LocalPath + @"\bgms\" + live.bgm_path; byte[] bgmBytes = File.ReadAllBytes(bgmRemotePath); File.WriteAllBytes(bgmLocalPath, bgmBytes); }
/// <summary> /// Save picture on file system /// </summary> /// <param name="pictureId">Picture identifier</param> /// <param name="pictureBinary">Picture binary</param> /// <param name="mimeType">MIME type</param> protected virtual void SavePictureInFile(int pictureId, byte[] pictureBinary, string mimeType) { string lastPart = GetFileExtensionFromMimeType(mimeType); string fileName = string.Format("{0}_0.{1}", pictureId.ToString("0000000"), lastPart); File.WriteAllBytes(GetPictureLocalPath(fileName), pictureBinary); }
public string Download(Image img) { Console.WriteLine("Downloading image..."); var base64Data = Regex.Match(img.Data, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value; var binData = Convert.FromBase64String(base64Data); img.Folder = img.Folder ?? ""; var path = Path.Combine(BASE_PHYSICAL_PATH, img.Folder); var filename = Path.Combine(path, img.Filename); if (!IOFile.Exists(filename)) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } IOFile.WriteAllBytes(filename, binData); Console.WriteLine("Image saved to {0}.", filename); return("Downloaded!"); } else { Console.WriteLine("The specified file already exists!"); return("The file already exists!"); } }
private void btnDownloadFile_Click(object sender, EventArgs e) { Guid fileId = new Guid(); string fileName = ""; try { if (tcFiles.SelectedTab.Name == "tpUserFiles") { fileId = (Guid)dgvUserFiles.SelectedRows[0].Cells[0].Value; fileName = dgvUserFiles.SelectedRows[0].Cells[1].Value.ToString(); } else if (tcFiles.SelectedTab.Name == "tpAllowedFiles") { fileId = (Guid)dgvAllowedFiles.SelectedRows[0].Cells[0].Value; fileName = dgvAllowedFiles.SelectedRows[0].Cells[1].Value.ToString(); } if (fileId != null) { using (var dialog = new SaveFileDialog()) { dialog.FileName = fileName.ToString(); if (dialog.ShowDialog() == DialogResult.OK) { var content = _client.DownloadFile((Guid)fileId); File.WriteAllBytes(dialog.FileName, content); } } } } catch (Exception exception) { MessageBox.Show($"File was not downloaded. Error message: {Environment.NewLine}{exception.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void Write_datetimeoffset() { var ds = new DataSet( new SchemaElement <DateTimeOffset>("timestamp_col") ) { new DateTimeOffset(new DateTime(2017, 1, 1, 12, 13, 22)), new DateTimeOffset(new DateTime(2017, 1, 1, 12, 13, 23)) }; //8 values for each column var uncompressed = new MemoryStream(); using (var writer = new ParquetWriter(uncompressed)) { writer.Write(ds, CompressionMethod.None); } #if DEBUG const string path = "c:\\tmp\\first.parquet"; F.WriteAllBytes(path, uncompressed.ToArray()); #endif }
private static void WriteArtworkFile(string directory, AlbumArtworkSaveFormat saveFormat, Track track, ImageCacheEntry albumArtwork) { string fileName = null; switch (saveFormat) { case AlbumArtworkSaveFormat.DontSave: break; case AlbumArtworkSaveFormat.AsCover: fileName = albumArtwork?.Picture.FileType.Append("cover"); break; case AlbumArtworkSaveFormat.AsArtistAlbum: fileName = albumArtwork?.Picture.FileType.Append($"{track.Artist} - {track.Album.Title}"); if (fileName != null) { fileName = PathHelpers.CleanFilename(fileName); } break; default: throw new ArgumentOutOfRangeException(); } if (fileName == null) { return; } SysFile.WriteAllBytes(Path.Combine(directory, fileName), albumArtwork.Data); }
public IActionResult LoadMusic(int Id) { using (var db = new Context()) { var track = db.Track.Include(x => x.SingerTrack) .ThenInclude(x => x.Singer) .Include(x => x.GenreTrack) .ThenInclude(x => x.Genre) .FirstOrDefault(x => x.ID == Id); if (track == null) { var ex = new Exception($"Track is not found by ID = {Id}"); _logger.LogWarning(ex, "", null); throw ex; } if (string.IsNullOrEmpty(track.Path)) { var ex = new Exception($"Track path is empty by ID = {Id}"); _logger.LogWarning(ex, "", null); throw ex; } var buf = FileIO.ReadAllBytes(Path.Combine(musicDir, track.Path)); var webPath1 = Path.Combine("audio", $"{track.ID}{Path.GetExtension(track.Path)}"); var webPath2 = Path.Combine("..\\..\\..\\", "audio", $"{track.ID}{Path.GetExtension(track.Path)}"); var path = Path.Combine(_env.WebRootPath, webPath1); FileIO.WriteAllBytes(path, buf); //special path for web //webPath = @"" + webPath.Replace("/", @""); return(Json(webPath2)); } }
public void WriteAssembly(String assembly, String path) { if (!File.Exists(path)) { File.WriteAllBytes(path, GetTextAssembly(assembly)); } }
public RepositorySession Start() { Metainfo metainfo; RepositoryData data = new RepositoryData(20000); using (FileSandbox temp = new FileSandbox(new EmptyFileLocator())) { MetainfoBuilder builder = new MetainfoBuilder(temp.Directory); string path = temp.CreateFile("debian-8.5.0-amd64-CD-1.iso"); File.WriteAllBytes(path, data.ToBytes()); builder.AddFile(path); metainfo = builder.ToMetainfo(); } FileSandbox sandbox = new FileSandbox(new EmptyFileLocator()); string destination = Path.Combine(sandbox.Directory, metainfo.Hash.ToString()); RepositoryService service = new RepositoryBuilder() .WithHash(metainfo.Hash) .WithDestination(destination) .WithFiles(files) .WithPipeline(pipeline) .WithMemory(new RepositoryMemoryImplementation()) .Build(); return(new RepositorySession(metainfo, service, sandbox, data)); }
private void bildSpeichernToolStripMenuItem_Click(object sender, EventArgs e) { if (saveFileDialog1.ShowDialog() == DialogResult.OK) { File.WriteAllBytes(saveFileDialog1.FileName, Data); } }
public void DownloadMaritimeReporter() { var myFile = new System.IO.StreamReader(@"\\WEBDEVELOPERS15\Projects\BpaNewsLetter\MaritimePropulsion\MaritimePropulsion.txt"); string myString = myFile.ReadToEnd(); using (StringReader reader = new StringReader(myString)) { string line; while ((line = reader.ReadLine()) != null) { try { string url = line; var dictionary = new Dictionary <String, String>(); var pdfFile = RequestHelper.GetImageFromUrl(line, dictionary); String fileName = ""; if (dictionary.ContainsKey("Content-Disposition")) { fileName = dictionary["Content-Disposition"].ToStr().Split(";".ToCharArray())[1].Replace("filename=", ""); } File.WriteAllBytes(String.Format(@"\\WEBDEVELOPERS15\Projects\BpaNewsLetter\MaritimePropulsion\{0}", fileName), pdfFile); } catch (Exception ex) { } } } }
public async Task <IActionResult> Edit(string id, ModVM mod) { var length = (int)mod.File.Length; var buffer = new byte[length]; mod.File.OpenReadStream().Read(buffer, 0, length); var entry = new Mod(); if (!entry.ExtractInfo(buffer)) { return(this.UnprocessableEntity()); } if (id != entry.Name) { return(this.NotFound()); } if (this.ModelState.IsValid) { var existing = this._context.Mod.Find(id); if (existing == null) { return(this.NotFound()); } var user = await this._userManager.GetUserAsync(this.User); if (!existing.Author.Split(", ").Contains(user.AuthorName)) { return(this.Forbid()); } existing.ExtractInfo(buffer, true); entry.UpdateTimeStamp = DateTime.UtcNow.ToString("yyyy-MM-dd hh:mm:ss"); this._logger.LogInformation($"User {user.UserName} ({user.AuthorName}) Update {existing.DisplayName} ({existing.Name})"); try { var filename = existing.FilePath(); if (FileIO.Exists(filename)) { FileIO.Delete(filename); } FileIO.WriteAllBytes(filename, buffer); this._context.Update(existing); await this._context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { throw; } return(this.RedirectToAction(nameof(Details), new { id = entry.Name })); } return(this.View(mod)); }
private string VersionFile(string path) { if (path == null) { throw new ArgumentException($"{nameof(path)} may not be null."); } var pdbPath = Path.ChangeExtension(path, "pdb"); var versionedPath = GetNewPluginPath(path); Directory.CreateDirectory(Path.GetDirectoryName(versionedPath)); Debug.Assert(versionedPath != null, $"{nameof(versionedPath)} != null"); File.Copy(path, versionedPath, true); if (File.Exists(pdbPath)) { var versionedPdbPath = Path.ChangeExtension(versionedPath, "pdb"); File.Copy(pdbPath, versionedPdbPath, true); versionedPdbPath = Path.GetFileName(versionedPdbPath); // Do not include full path when patching dll // Update .pdb path in a newly copied file var pathBytes = Encoding.ASCII.GetBytes(Path.GetFileName(pdbPath)); // Does this work with i18n paths? var dllBytes = File.ReadAllBytes(versionedPath); int i; for (i = 0; i < dllBytes.Length; i++) { if (dllBytes.Skip(i).Take(pathBytes.Length).SequenceEqual(pathBytes)) // I know its slow ¯\_(ツ)_/¯ { if (dllBytes[i + pathBytes.Length] != 0) // Check for null terminator { continue; } while (dllBytes[--i] != 0) { // We found just a file name. Time to walk back to find a start of the string. This is // required because dll is executing from non-original directory and pdb path points // somewhere else we can not predict. } i++; // Copy full pdb path var newPathBytes = Encoding.ASCII.GetBytes(versionedPdbPath); newPathBytes.CopyTo(dllBytes, i); dllBytes[i + newPathBytes.Length] = 0; break; } } if (i == dllBytes.Length) { return(null); } File.WriteAllBytes(versionedPath, dllBytes); } return(versionedPath); }
private static void ExtractResources() { string assemblyLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var assem = Assembly.GetExecutingAssembly(); string resourceName = assem.GetManifestResourceNames().FirstOrDefault(rn => rn.Contains(ExtractPrefix)); int extractPosition = resourceName.IndexOf(ExtractPrefix, StringComparison.Ordinal); var dllName = resourceName.Substring(extractPosition + ExtractPrefix.Length); string assemblyFullName = Path.Combine(assemblyLocation, dllName); if (File.Exists(assemblyFullName)) { return; } if (resourceName == null) { return; } using (var stream = assem.GetManifestResourceStream(resourceName)) { Byte[] assemblyData = new Byte[stream.Length]; stream.Read(assemblyData, 0, assemblyData.Length); File.WriteAllBytes(assemblyFullName, assemblyData); } }
public static void Write(FileType fileType, string path, Track track) { ImageFile artworkFile = null; var url = track.Album.CoverUri.ToString(); if (ImageCache.Instance.HasItem(url) && ImageCache.Instance.Get(url) != null) { artworkFile = ImageCache.Instance.Get(track.Album.CoverUri.ToString()); } using (var file = File.Create(new File.LocalFileAbstraction(path), fileType.MimeType, ReadStyle.Average)) { file.Tag.Title = track.Title; file.Tag.Performers = new[] { track.Artist.Name }; if (track.Album.Artist != null) { file.Tag.AlbumArtists = new[] { track.Album.Artist.Name }; } file.Tag.Genres = new[] { track.Genre }; file.Tag.Album = track.Album.Title; file.Tag.Track = (uint)track.TrackNumber; file.Tag.TrackCount = (uint)(track.Album.GetNumberOfTracksOnDisc(track.DiscNumber) ?? 0); file.Tag.Disc = (uint)track.DiscNumber; file.Tag.DiscCount = (uint)(track.Album.GetTotalDiscs() ?? 0); file.Tag.Year = (uint)track.Year; file.Tag.Copyright = CopyrightText; file.Tag.Comment = CopyrightText; if (artworkFile != null) { file.Tag.Pictures = new IPicture[] { new Picture(new ByteVector(artworkFile.Data)) }; } file.Save(); } string fileName = null; switch (Program.DefaultSettings.Settings.AlbumArtworkSaveFormat) { case AlbumArtworkSaveFormat.DontSave: break; case AlbumArtworkSaveFormat.AsCover: fileName = artworkFile?.FileType.Append("cover"); break; case AlbumArtworkSaveFormat.AsArtistAlbum: fileName = artworkFile?.FileType.Append($"{track.Artist} - {track.Album.Title}"); break; default: throw new ArgumentOutOfRangeException(); } if (fileName != null && artworkFile != null) { var parentDir = Path.GetDirectoryName(path); SysFile.WriteAllBytes(Path.Combine(parentDir, fileName), artworkFile.Data); } }
public void ProcessFile(string path, string password, long totalSize) { var webPath = Settings.Get("WebServer").WebFilePath.ToString(); var tempFolderPath = webPath + "temp\\"; if (!Directory.Exists(tempFolderPath)) { Directory.CreateDirectory(tempFolderPath); } var file = new FileInfo(path); file.Directory?.Create(); // If the directory already exists, this method does nothing. var fileName = Path.GetFileName(path); var ip = NetworkService.GetIPv4Address(); var port = (int)Settings.Get("WebServer").WebServerPort; var data = File.ReadAllBytes(path); var encryptedFile = _builder.PackFile(password, data); try { if (encryptedFile != null) { var tempPath = Path.Combine(tempFolderPath, fileName); File.WriteAllBytes(tempPath, encryptedFile); var tempWebPath = $"http://{ip}:{port}/temp/{fileName}"; var downloadData = new { tempWebPath, totalSize }; _builder.WriteMessage(downloadData); } else { var errorData = new { error = true, message = "Unable to encrypt file" }; _builder.WriteMessage(errorData); } } catch ( Exception e) { var exceptionData = new { error = true, message = e.Message }; _builder.WriteMessage(exceptionData); } }
/// <summary> /// Encodes the ImageData and writes it to the path. /// </summary> /// <param name="path">The filename to write the file to.</param> /// <param name="imageData">The imageData to write the file to. </param> /// <param name="format">The format to encode the image as.</param> /// <returns></returns> public static void EncodeToFile(string path, ImageData imageData, ImageFormat format) { Check.ArgumentNull(path, "path"); Check.ArgumentNull(imageData, "imageData"); var fileData = imageData.Encode(format); SFile.WriteAllBytes(path, fileData.GetBytes()); }
public static async Task SaveEmbeddedResourceAsFileAsync(this Assembly assembly, string embeddedResourceName, string path = null) { using var resourceStream = assembly.GetManifestResourceStream(embeddedResourceName) ?? throw new InvalidOperationException("Could not find embedded resource."); using var ms = new MemoryStream(); await resourceStream.CopyToAsync(ms); File.WriteAllBytes(path ?? embeddedResourceName, ms.ToArray()); }
private static string WriteImage(string directory, Task <ImageEntry> t, string filename = null) { filename ??= t.Result.Url.Segments.Last(); var destination = Path.Combine(directory, filename); File.WriteAllBytes(destination, t.Result.Data); return(destination); }
public MetashareSession Start() { Metainfo metainfo; byte[] bytes = Bytes.Random(20000); using (FileSandbox temp = new FileSandbox(new EmptyFileLocator())) { MetainfoBuilder builder = new MetainfoBuilder(temp.Directory); string path = temp.CreateFile("debian-8.5.0-amd64-CD-1.iso"); File.WriteAllBytes(path, bytes); builder.AddFile(path); metainfo = builder.ToMetainfo(out bytes); } FileSandbox sandbox = new FileSandbox(new EmptyFileLocator()); string destination = Path.Combine(sandbox.Directory, metainfo.Hash.ToString()); File.WriteAllBytes(destination + ".metainfo", bytes); CoordinatorService glue = new CoordinatorBuilder() .WithHash(metainfo.Hash) .WithMemory(new MemoryBuilder().Build()) .WithPlugin(new MetadataPlugin(new MetadataHooks())) .Build(); MetafileService metafile = new MetafileBuilder() .WithHash(metainfo.Hash) .WithDestination(destination + ".metainfo") .WithFiles(files) .WithPipeline(pipeline) .Build(); MetashareService service = new MetashareBuilder() .WithHash(metainfo.Hash) .WithPipeline(pipeline) .WithGlue(glue) .WithMetafile(metafile) .Build(); TaskCompletionSource <bool> onVerified = new TaskCompletionSource <bool>(); metafile.Hooks.OnMetafileVerified += _ => onVerified.SetResult(true); metafile.Start(); metafile.Verify(); onVerified.Task.Wait(5000); return(new MetashareSession(service)); }
public void сheckForUpdates(bool autoCheck) { try { WebClient client = new WebClient(); Stream stream = client.OpenRead("https://raw.githubusercontent.com/Sigmanor/Crypto-Notepad/master/version.txt"); StreamReader reader = new StreamReader(stream); string content = reader.ReadToEnd(); string version = Application.ProductVersion; string exePath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\"; int appVersion = Convert.ToInt32(version.Replace(".", "")), serverVersion = Convert.ToInt32(content.Replace(".", "")); if (serverVersion > appVersion) { MainMenu.Invoke((Action) delegate { using (new CenterWinDialog(this)) { DialogResult res = new DialogResult(); res = MessageBox.Show("New version is available. Install it now?", "Update", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (res == DialogResult.Yes) { File.WriteAllBytes(exePath + "Ionic.Zip.dll", Properties.Resources.Ionic_Zip); File.WriteAllBytes(exePath + "Updater.exe", Properties.Resources.Updater); var pr = new Process(); pr.StartInfo.FileName = exePath + "Updater.exe"; pr.StartInfo.Arguments = "/u"; pr.Start(); Application.Exit(); } } }); } if (serverVersion <= appVersion && autoCheck == true) { MainMenu.Invoke((Action) delegate { using (new CenterWinDialog(this)) { MessageBox.Show("Crypto Notepad is up to date.", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information); } }); } } catch { return; } }
void SetupFfmpeg() { try { _ffmpegPath = Path.Combine(Path.GetTempPath(), "ffmpeg.exe"); File.WriteAllBytes(_ffmpegPath, Resources.ffmpeg); } catch (Exception) { } }
public long Write(string key, byte[] content) { var path = ComputePath(key); var directory = Path.GetDirectoryName(path); EnsureDirectoryExists(directory, true); //TODO : replace true by Create ??? IOFile.WriteAllBytes(path, content); return(content.LongLength); }
/// <summary> /// Записывает текст в файл. Если файла нет, то он будет создан. /// Если есть, то его содержимое будет перезаписано. /// </summary> /// <param name="text">Текст.</param> /// <param name="path">Путь до файла.</param> /// <exception cref="Exception">Произошла ошибка записи.</exception> private static void WriteFile(string text, string path) { try { var bytes = Encoding.UTF8.GetBytes(text); File.WriteAllBytes(path, bytes); } catch (Exception e) { throw new Exception("Не удалось записать файл.", e); } }
public void ProcessFile(string path, string password, long totalSize) { var webPath = Settings.Get("WebServer").WebFilePath.ToString(); var file = new FileInfo(path); file.Directory?.Create(); // If the directory already exists, this method does nothing. var fileName = Path.GetFileName(path); var ip = NetworkUtilities.GetIPv4Address(); var httpPort = HttpServer.GlobalPort; var data = File.ReadAllBytes(path); var encryptedFile = _serializator.SerializeFile(_client, password, data); try { if (encryptedFile != null) { var tempPath = Path.Combine(webPath + "temp\\", fileName); File.WriteAllBytes(tempPath, encryptedFile); var tempWebPath = $"http://{ip}:{httpPort}/temp/{fileName}"; var downloadData = new { tempWebPath, totalSize }; _serializator.Serialize(_client, _packet.Endpoint, _packet.SyncKey, downloadData); } else { var errorData = new { error = true, message = "Unable to encrypt file" }; _serializator.Serialize(_client, _packet.Endpoint, _packet.SyncKey, errorData); } } catch ( Exception e) { var exceptionData = new { error = true, message = e.Message }; _serializator.Serialize(_client, _packet.Endpoint, _packet.SyncKey, exceptionData); } }
public static void WriteAllBytes(string path, byte[] data) { //https://github.com/peteraritchie/LongPath/issues/48 if (path != null && path.Length < 240) { System.IO.File.WriteAllBytes(path, data); } else { MyFile.WriteAllBytes(path, data); } }
private void saveImage(byte[] imageData) { string filename = settings.albumArtFilename; if (imageData != null) { File.WriteAllBytes(filename, imageData); } else { File.Delete(filename); } }
public void Save(string path) { // Write ROM icon (uses NSMBe to generate icon data) DoWithNSMBeROM(Path, WriteROMIcon); // Write filesystem ROM.FromFileSystem(ROMFs); // Save the ROM var data = ROM.Write(); SystemFile.WriteAllBytes(path, data); }
public void Convert(MediaConvertModel model) { VideoConvertedCommand command = null; try { var tempFilePath = Path.GetTempFileName(); File.WriteAllBytes(tempFilePath, model.File.FileBytes); var inputFile = new MediaFile { Filename = tempFilePath }; var outputFile = new MediaFile { Filename = Path.ChangeExtension(tempFilePath, Mp4ExtensionName) }; using (_engine) { _engine.GetMetadata(inputFile); var options = new ConversionOptions(); _engine.Convert(inputFile, outputFile, options); } File.Delete(inputFile.Filename); command = new VideoConvertedCommand { Success = true, ConvertedFilePath = outputFile.Filename, MediaId = model.MediaId }; } catch (Exception ex) { command = new VideoConvertedCommand() { MediaId = model.MediaId, Success = false, Message = new VideoConvertedCommandMessageModel() { ExceptionMessage = ex.Message, StackTrace = ex.StackTrace, FileName = model.File.FileName } }; } finally { _commandPublisher.Publish(command); } }
public void Convert(MediaConvertModel model) { VideoConvertedCommand command = null; try { var tempFilePath = Path.GetTempFileName(); File.WriteAllBytes(tempFilePath, model.File.FileBytes); var inputFile = new MediaFile { Filename = tempFilePath }; var outputFile = new MediaFile { Filename = Path.ChangeExtension(tempFilePath, Mp4ExtensionName) }; using (var engine = new Engine(HostingEnvironment.MapPath(IntranetConstants.FfmpegRelativePath))) { engine.GetMetadata(inputFile); var options = new Uintra.Core.MediaToolkit.Options.ConversionOptions(); engine.Convert(inputFile, outputFile, options); } File.Delete(inputFile.Filename); command = new VideoConvertedCommand { Success = true, ConvertedFilePath = outputFile.Filename, MediaId = model.MediaId }; } catch (Exception ex) { command = new VideoConvertedCommand { MediaId = model.MediaId, Success = false, Message = new VideoConvertedCommandMessageModel { ExceptionMessage = ex.Message, StackTrace = ex.StackTrace, FileName = model.File.FileName } }; } finally { _commandPublisher.Publish(command); } }