/// <summary> /// Sets the ass font. /// </summary> /// <param name="file">The file.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <c>System.Threading.CancellationToken.None</c>.</param> /// <returns>Task.</returns> private async Task SetAssFont(string file, CancellationToken cancellationToken = default) { _logger.LogInformation("Setting ass font within {File}", file); string text; Encoding encoding; using (var fileStream = AsyncFile.OpenRead(file)) using (var reader = new StreamReader(fileStream, true)) { encoding = reader.CurrentEncoding; text = await reader.ReadToEndAsync().ConfigureAwait(false); } var newText = text.Replace(",Arial,", ",Arial Unicode MS,", StringComparison.Ordinal); if (!string.Equals(text, newText, StringComparison.Ordinal)) { var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous); var writer = new StreamWriter(fileStream, encoding); await using (fileStream.ConfigureAwait(false)) await using (writer.ConfigureAwait(false)) { await writer.WriteAsync(newText.AsMemory(), cancellationToken).ConfigureAwait(false); } } }
private async Task SaveToFileAsync(Stream stream, string path) { var directory = Path.GetDirectoryName(path) ?? throw new ArgumentException($"Provided path ({path}) is not valid.", nameof(path)); Directory.CreateDirectory(directory); // On Windows, saving the file will fail if the file is hidden or readonly FileSystem.SetAttributes(path, false, false); var fileStreamOptions = new FileStreamOptions() { Mode = FileMode.Create, Access = FileAccess.Write, Share = FileShare.None, PreallocationSize = stream.Length, Options = FileOptions.Asynchronous }; var filestream = new FileStream(path, fileStreamOptions); await using (filestream.ConfigureAwait(false)) { await stream.CopyToAsync(filestream).ConfigureAwait(false); } if (ConfigurationManager.Configuration.SaveMetadataHidden) { SetHidden(path, true); } }
private async Task ExtractFilesAsync() { while (filesToExtract.Count > 0) { cancellationTokenSource.Token.ThrowIfCancellationRequested(); var packageFile = filesToExtract.Dequeue(); Invoke((Action)(() => { extractProgressBar.Value = 100 - (int)((filesToExtract.Count / (float)initialFileCount) * 100.0f); extractStatusLabel.Text = $"Extracting {packageFile.GetFullPath()}"; })); var filePath = Path.Combine(path, packageFile.GetFullPath()); package.ReadEntry(packageFile, out var output, false); Directory.CreateDirectory(Path.GetDirectoryName(filePath)); if (decompile && filePath.EndsWith("_c", StringComparison.Ordinal)) { using (var resource = new Resource { FileName = filePath, }) using (var memory = new MemoryStream(output)) { try { resource.Read(memory); var extension = FileExtract.GetExtension(resource); if (extension == null) { filePath = filePath.Substring(0, filePath.Length - 2); } else { filePath = Path.ChangeExtension(filePath, extension); } output = FileExtract.Extract(resource).ToArray(); } catch (Exception e) { Console.WriteLine($"Failed to extract '{packageFile.GetFullPath()}' - {e.Message}"); continue; } } } var stream = new FileStream(filePath, FileMode.Create); await using (stream.ConfigureAwait(false)) { await stream.WriteAsync(output, cancellationTokenSource.Token).ConfigureAwait(false); } } }
private async Task SendFileAsync(string filePath, HttpResponse response, long offset, long?count) { var fileInfo = GetFileInfo(filePath); if (offset < 0 || offset > fileInfo.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, string.Empty); } if (count.HasValue && (count.Value < 0 || count.Value > fileInfo.Length - offset)) { throw new ArgumentOutOfRangeException(nameof(count), count, string.Empty); } // Copied from SendFileFallback.SendFileAsync const int BufferSize = 1024 * 16; var fileStream = new FileStream( filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize: BufferSize, options: FileOptions.Asynchronous | FileOptions.SequentialScan); await using (fileStream.ConfigureAwait(false)) { fileStream.Seek(offset, SeekOrigin.Begin); await StreamCopyOperation .CopyToAsync(fileStream, response.Body, count, BufferSize, CancellationToken.None) .ConfigureAwait(true); } }
internal async Task Save() { FileStream file = File.OpenWrite("config.json"); await using (file.ConfigureAwait(false)) { await JsonSerializer.SerializeAsync(file, this).ConfigureAwait(false); } }
/// <inheritdoc /> public async Task SaveAsync(BaseItem item, CancellationToken cancellationToken) { var path = GetSavePath(item); var directory = Path.GetDirectoryName(path) ?? throw new InvalidDataException($"Provided path ({path}) is not valid."); Directory.CreateDirectory(directory); // On Windows, savint the file will fail if the file is hidden or readonly FileSystem.SetAttributes(path, false, false); var fileStreamOptions = new FileStreamOptions() { Mode = FileMode.Create, Access = FileAccess.Write, Share = FileShare.None }; var filestream = new FileStream(path, fileStreamOptions); await using (filestream.ConfigureAwait(false)) { var settings = new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8, Async = true }; var writer = XmlWriter.Create(filestream, settings); await using (writer.ConfigureAwait(false)) { var root = GetRootElementName(item); await writer.WriteStartDocumentAsync(true).ConfigureAwait(false); await writer.WriteStartElementAsync(null, root, null).ConfigureAwait(false); var baseItem = item; if (baseItem != null) { await AddCommonNodesAsync(baseItem, writer).ConfigureAwait(false); } await WriteCustomElementsAsync(item, writer).ConfigureAwait(false); await writer.WriteEndElementAsync().ConfigureAwait(false); await writer.WriteEndDocumentAsync().ConfigureAwait(false); } } if (ConfigurationManager.Configuration.SaveMetadataHidden) { SetHidden(path, true); } }
/// <summary> /// Waits for a minimum number of segments to be available. /// </summary> /// <param name="playlist">The playlist string.</param> /// <param name="segmentCount">The segment count.</param> /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param> /// <returns>A <see cref="Task"/> indicating the waiting process.</returns> public static async Task WaitForMinimumSegmentCount(string playlist, int?segmentCount, ILogger logger, CancellationToken cancellationToken) { logger.LogDebug("Waiting for {0} segments in {1}", segmentCount, playlist); while (!cancellationToken.IsCancellationRequested) { try { // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written var fileStream = new FileStream( playlist, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, FileOptions.SequentialScan); await using (fileStream.ConfigureAwait(false)) { using var reader = new StreamReader(fileStream); var count = 0; while (!reader.EndOfStream) { var line = await reader.ReadLineAsync().ConfigureAwait(false); if (line == null) { // Nothing currently in buffer. break; } if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1) { count++; if (count >= segmentCount) { logger.LogDebug("Finished waiting for {0} segments in {1}", segmentCount, playlist); return; } } } } await Task.Delay(100, cancellationToken).ConfigureAwait(false); } catch (IOException) { // May get an error if the file is locked } await Task.Delay(50, cancellationToken).ConfigureAwait(false); } }
private async Task TrySaveToFiles(Stream stream, List <string> savePaths) { List <Exception> exs = null; foreach (var savePath in savePaths) { _logger.LogInformation("Saving subtitles to {SavePath}", savePath); _monitor.ReportFileSystemChangeBeginning(savePath); try { Directory.CreateDirectory(Path.GetDirectoryName(savePath)); var fileOptions = AsyncFile.WriteOptions; fileOptions.Mode = FileMode.CreateNew; fileOptions.PreallocationSize = stream.Length; var fs = new FileStream(savePath, fileOptions); await using (fs.ConfigureAwait(false)) { await stream.CopyToAsync(fs).ConfigureAwait(false); } return; } catch (Exception ex) { // Bug in analyzer -- https://github.com/dotnet/roslyn-analyzers/issues/5160 #pragma warning disable CA1508 (exs ??= new List <Exception>()).Add(ex); #pragma warning restore CA1508 } finally { _monitor.ReportFileSystemChangeComplete(savePath, false); } stream.Position = 0; } if (exs != null) { throw new AggregateException(exs); } }
private async void btnSend_Click(object sender, EventArgs e) { using (var client = new TcpClient(tboxAddress.Text, ((int)(nudPort.Value)))) { var ns = client.GetStream(); await using (ns.ConfigureAwait(false)) { var bw = new BinaryWriter(ns); await using (bw.ConfigureAwait(false)) { bw.Write(cboxAllowEscape.Checked); var fs = new FileStream(tboxFile.Text, FileMode.Open, FileAccess.Read, FileShare.Read); await using (fs.ConfigureAwait(false)) { bw.Write(fs.Length); await fs.CopyToAsync(ns); } } } } this.Invoke(new Action(this.Close)); }
private static async ValueTask SaveZoneIdentifier(string filename, IPAddress?ipa) { var fs = new FileStream(filename + ":Zone.Identifier", FileMode.Create, FileAccess.Write, FileShare.None); await using (fs.ConfigureAwait(false)) { var sw = new StreamWriter(fs); await using (sw.ConfigureAwait(false)) { await sw.WriteLineAsync("[ZoneTransfer]"); await sw.WriteLineAsync("ZoneId=3"); if (ipa is not null) { await sw.WriteLineAsync($"HostIpAddress={ipa}"); } await sw.WriteLineAsync("CocoaLogViewer=FormReceiver"); } } }
private async Task ExtractSystemProfilesAsync() { var namespaceName = GetType().Namespace + ".Profiles.Xml."; var systemProfilesPath = SystemProfilesPath; foreach (var name in _assembly.GetManifestResourceNames()) { if (!name.StartsWith(namespaceName, StringComparison.Ordinal)) { continue; } var path = Path.Join( systemProfilesPath, Path.GetFileName(name.AsSpan()).Slice(namespaceName.Length)); // The stream should exist as we just got its name from GetManifestResourceNames using (var stream = _assembly.GetManifestResourceStream(name) !) { var length = stream.Length; var fileInfo = _fileSystem.GetFileInfo(path); if (!fileInfo.Exists || fileInfo.Length != length) { Directory.CreateDirectory(systemProfilesPath); var fileOptions = AsyncFile.WriteOptions; fileOptions.Mode = FileMode.Create; fileOptions.PreallocationSize = length; var fileStream = new FileStream(path, fileOptions); await using (fileStream.ConfigureAwait(false)) { await stream.CopyToAsync(fileStream).ConfigureAwait(false); } } } } // Not necessary, but just to make it easy to find Directory.CreateDirectory(UserProfilesPath); }
internal static async Task <Configuration?> Load() { if (!File.Exists("config.json")) { return(null); } Configuration?loadedConfig; FileStream file = File.OpenRead("config.json"); await using (file.ConfigureAwait(false)) { try { loadedConfig = await JsonSerializer.DeserializeAsync <Configuration>(file).ConfigureAwait(false); } catch { return(null); } } return(loadedConfig); }
/// <summary> /// JSON形式の言語情報ファイルを非同期的に読み込みます。 /// </summary> /// <param name="path">JSON形式の言語情報ファイルへのパスです。</param> /// <param name="cultureInfo">JSON形式の言語情報ファイルのカルチャです。</param> /// <returns> /// ファイルが存在する場合は言語情報ファイルを含む非同期操作オブジェクトを返します。 /// 存在しない場合は<see langword="null"/>を含む非同期操作オブジェクトを返します。 /// </returns> /// <exception cref="System.ArgumentNullException"/> /// <exception cref="System.IO.IOException"/> public static async ValueTask <JsonLanguageData?> LoadFileAsync(string path, CultureInfo cultureInfo) { path.EnsureNotNull(nameof(path)); cultureInfo.EnsureNotNull(nameof(cultureInfo)); if (File.Exists(path)) { try { var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); await using (fs.ConfigureAwait(false)) { using (var sr = new StreamReader(fs, Encoding.UTF8, true)) { return(new(await sr.ReadToEndAsync(), cultureInfo)); } } } catch (Exception e) { throw new IOException(Resources.JsonLanguageData_LoadFileAsync_IOException, e); } } else { return(null); } }
private async void FormReceiver_Load(object sender, EventArgs e) { this.Text = LanguageData.Current.FormReceiver_Title; labelDescription.Text = LanguageData.Current.FormReceiver_Description; var listener = new TcpListener(await GetLocalIPAddress(), 0); listener.Start(); if (listener.LocalEndpoint is IPEndPoint ipep) { textBox.Text = $"IP : {ipep.Address}\r\nPort: {ipep.Port}"; } else { textBox.Text = listener.LocalEndpoint?.ToString(); } try { bool allowEscape; while (!_cts.IsCancellationRequested) { string temp = Path.GetTempFileName(); IPAddress?ipa = null; byte[] buf = new byte[1024]; using (var client = await Task.Run(listener.AcceptTcpClientAsync, _cts.Token)) { var ns = client.GetStream(); if (client.Client.RemoteEndPoint is IPEndPoint ep) { ipa = ep.Address; } await using (ns.ConfigureAwait(false)) { using (var br = new BinaryReader(ns)) { while (!ns.DataAvailable) { await Task.Yield(); } allowEscape = br.ReadBoolean(); long len = br.ReadInt64(); var fs = new FileStream(temp, FileMode.Create, FileAccess.Write, FileShare.None); await using (fs.ConfigureAwait(false)) { while (fs.Length < len) { while (!ns.DataAvailable) { await Task.Yield(); } int bytes = await ns.ReadAsync(buf.AsMemory(), _cts.Token); if (bytes > 0) { await fs.WriteAsync(buf.AsMemory(0..bytes), _cts.Token); } } } } } } await SaveZoneIdentifier(temp, ipa); await _owner.OpenFileAsync(temp, allowEscape); } } finally { listener.Stop(); } }