public override async Task <bool> Save(FilesGroup filesGroup, FileWriteMode writeMode) { var endpointPath = writeMode switch { FileWriteMode.Override => Endpoints.UpdateEndpoint, FileWriteMode.CreateNew => Endpoints.CreateEndpoint, _ => throw new ArgumentOutOfRangeException(nameof(writeMode), writeMode, "such operation can't be done") }; var multipartFormDataContent = new MultipartFormDataContent(); var streamData = await Task.WhenAll(filesGroup.RelatedFiles.Select(MakeStreamContent)).ConfigureAwait(false); var fullBookmarkPath = GetFullPath(filesGroup); var stringContent = new StringContent(fullBookmarkPath); foreach (var streamContent in streamData) { var ext = streamContent.Headers.First(kvp => kvp.Key == "Extension").Value.First() !; multipartFormDataContent.Add(streamContent, EnumsHelper.ParseType(ext).ToString(), $"{filesGroup.Name}.{ext}"); } multipartFormDataContent.Add(stringContent, "bookmarkPath"); using var httpRequestMessage = await CreateHttpRequestMessageWithAuthHeader(HttpMethod.Post, endpointPath, multipartFormDataContent).ConfigureAwait(false); using var responseMessage = await _httpClient.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false); return(responseMessage.IsSuccessStatusCode); }
private async Task <IActionResult> StoreBookmark(IFormFileCollection formFileCollection, string bookmarkPath, DateTime lastWriteDate, FileWriteMode writeMode) { FormatPath(ref bookmarkPath); lastWriteDate = new DateTime(lastWriteDate.Year, lastWriteDate.Month, lastWriteDate.Day, lastWriteDate.Hour, lastWriteDate.Minute, lastWriteDate.Second, lastWriteDate.Kind); // truncate milliseconds off var dataDictionary = new Dictionary <BookmarkFileType, Stream>(); foreach (var formFile in formFileCollection) { var formFileHeader = formFile.Headers["Extension"]; dataDictionary.Add(EnumsHelper.ParseType(formFileHeader), formFile.OpenReadStream()); } var fileTypes = formFileCollection.Select(formFile => formFile.Headers["Extension"].ToString()).Select(EnumsHelper.ParseType).ToArray(); if (EnumsHelper.RecognizeFilesGroupType(fileTypes) == null) { return(BadRequest("bookmark type isn't recognized")); } var fakeFilesGroup = _storageService.MakeFake(bookmarkPath); var filesGroup = new ProxyFilesGroup(fakeFilesGroup, dataDictionary, lastWriteDate); var result = await _storageService.Save(filesGroup, writeMode); return(result ? (IActionResult)Ok() : BadRequest()); }
public static bool WriteFile(string path, string fileName, string data, FileWriteMode mode) { bool retValue = false; string dataPath = path; try { if (!System.IO.Directory.Exists(dataPath)) { System.IO.Directory.CreateDirectory(dataPath); } dataPath += fileName; switch (mode) { case FileWriteMode.Open: retValue = false; break; case FileWriteMode.CreateOverwirte: System.IO.File.WriteAllText(dataPath, data); break; case FileWriteMode.Append: System.IO.File.AppendAllText(dataPath, data); break; } retValue = true; } catch (System.Exception ex) { Debug.LogError("File Write Error\n" + ex.Message); retValue = false; Debug.LogError(ex.Message); } return(retValue); }
public FileToFileRunner(ExifToolOptions opts, string src, string dst) : base(opts) { _src = src ?? throw new ArgumentNullException(nameof(src)); _dst = dst ?? throw new ArgumentNullException(nameof(dst)); _writeMode = FileWriteMode.WriteNew; }
/// <summary> /// Creates or opens the specified file for writing using UTF-8 encoding. /// /// Append vs. overwrite behavior is determined by write mode. /// /// This method throws an exception if path is null, an invalid path, /// a zero-length string, or if the caller does not have sufficient /// permissions to write to the specified file. /// </summary> public TextWriter GetTextWriter(string filePath, FileWriteMode writeMode) { // Create full path by combining with output folder path string fullFilePath = Path.Combine(FolderPath, filePath); string fullFolderPath = Path.GetDirectoryName(fullFilePath); // Check if directory exists, if not create if (!Directory.Exists(fullFolderPath)) { Directory.CreateDirectory(fullFolderPath); } switch (writeMode) { case FileWriteMode.Append: return(new StreamWriter(fullFilePath)); case FileWriteMode.Replace: if (File.Exists(fullFilePath)) { File.Delete(fullFilePath); } return(new StreamWriter(fullFilePath)); case FileWriteMode.CreateNew: if (File.Exists(fullFilePath)) { Context.Log.Error($"File {fullFilePath} already exists."); } return(new StreamWriter(fullFilePath)); default: throw new Exception($"FileMode={writeMode} is not supported."); } }
public void ChangeWriteMode(FileWriteMode mode) { switch (mode) { case FileWriteMode.Append: if (!appending) { appending = true; CloseWriter(); writer = new StreamWriter(filePath, appending); } break; case FileWriteMode.Overwrite: if (appending) { appending = false; CloseWriter(); writer = new StreamWriter(filePath, appending); } break; default: throw new ArgumentOutOfRangeException(nameof(mode), mode, null); } }
/// <summary>Appends or overwrites the specified file depending on write mode.</summary> private static void SaveText(this IFolder obj, string filePath, string text, FileWriteMode writeMode) { TextWriter textWriter = obj.GetTextWriter(filePath, writeMode); textWriter.Write(text); textWriter.Flush(); }
/// <summary> /// 构造函数。 /// </summary> /// <param name="filePath">文件路径。</param> /// <param name="bytes">写入的内容。</param> /// <param name="mode">文件写入模式<see cref="FileWriteMode"/></param> public FileWriteTask(string filePath, byte[] bytes, FileWriteMode mode = FileWriteMode.OVERRIDE) : base(true) { this.filePath = filePath; this.bytes = bytes; this.mode = mode; this.stream = null; this.completed = false; }
bool IsOverwriteMode(FileWriteMode mode) { switch (mode) { case FileWriteMode.OverwriteOriginal: case FileWriteMode.OverwriteOriginalInPlace: return(true); default: return(false); } }
public FileToFileRunner(ExifToolOptions opts, string src, FileWriteMode writeMode) : base(opts) { _src = src ?? throw new ArgumentNullException(nameof(src)); _dst = src; if (!IsOverwriteMode(writeMode)) { throw new ArgumentException("Please specify one of the Overwrite FileWriteModes when using this constructor."); } _writeMode = writeMode; }
protected string GetOverwriteArgument(FileWriteMode mode) { switch (mode) { case FileWriteMode.OverwriteOriginalInPlace: return("-overwrite_original_in_place"); case FileWriteMode.OverwriteOriginal: return("-overwrite_original"); default: throw new InvalidOperationException("Unexpected overwrite mode!"); } }
private async Task <bool> SaveFile(FileProfile fileProfile, FileWriteMode writeMode) { using var fileInputStream = await fileProfile.GetData().ConfigureAwait(false); var pathToSave = GetFullPath(fileProfile); if (writeMode == FileWriteMode.CreateNew && File.Exists(pathToSave)) { return(false); } if (writeMode == FileWriteMode.Override && !File.Exists(pathToSave)) { return(false); } var fileMode = writeMode switch { FileWriteMode.Override => FileMode.Create, FileWriteMode.CreateNew => FileMode.CreateNew, _ => throw new ArgumentOutOfRangeException(nameof(writeMode), writeMode, null) }; try { Directory.CreateDirectory(Path.GetDirectoryName(pathToSave) !); using (var outputStream = new FileStream(pathToSave, fileMode)) { await fileInputStream.CopyToAsync(outputStream).ConfigureAwait(false); } File.SetCreationTimeUtc(pathToSave, fileProfile.LastTimeUtc); File.SetLastWriteTimeUtc(pathToSave, fileProfile.LastTimeUtc); return(true); } catch { return(false); } }
public static bool WriteFile(string fileName, string data, FileWriteMode mode) { return(WriteFile(DataPath(), fileName, data, mode)); }
/// <summary> /// Creates file for write /// </summary> /// <param name="in_data">Function parameter bytes</param> private void CasCreate(byte in_data) { if (m_write_data_index == 0) { m_filename_length_param = in_data; m_filename_param = ""; } // store filename character int filename_index = m_write_data_index - 1; if (filename_index >= 0 && filename_index < m_filename_length_param) { m_filename_param += (char)in_data; } // if last character is received if (filename_index + 1 == m_filename_length_param) { // create file if (m_write_file == null) { string filename = GetFilePath(m_filename_param); if (File.Exists(filename)) { EndFunction(CoProcessorConstants.ERR_FILE_EXISTS); } else { if (!Directory.Exists(Path.GetDirectoryName(filename))) { EndFunction(CoProcessorConstants.ERR_NO_PATH); } else { // try to create file try { m_write_stream = File.Open(filename, FileMode.Create, FileAccess.ReadWrite); m_write_file = new BinaryWriter(m_write_stream); // In case of CAS file write UPM header if (string.Compare(Path.GetExtension(filename), ".CAS", true) == 0) { m_write_mode = FileWriteMode.CASFile; // create and write empty upm header (close will update it) TVCFileTypes.CASUPMHeaderType upm_header = new TVCFileTypes.CASUPMHeaderType(); upm_header.FileType = TVCFileTypes.CASBlockHeaderFileUnbuffered; upm_header.CopyProtect = 0; upm_header.BlockNumber = 0; upm_header.LastBlockBytes = 0; m_write_file.Write(upm_header); } else { m_write_mode = FileWriteMode.File; } // gererate result file name filename = Path.GetFileNameWithoutExtension(filename); m_filename_param = TVCCharacterCodePage.UNICODEStringToTVCString(filename); SetReadResult(CoProcessorReadFilename); } catch { EndFunction(CoProcessorConstants.ERR_FILE_EXISTS); } } } } else { // if file is already created EndFunction(CoProcessorConstants.ERR_ALREADY_OPENED); } } m_write_data_index++; }
public override Task <bool> Save(FilesGroup filesGroup, FileWriteMode writeMode) { return(filesGroup.RelatedFiles .Select(profile => SaveFile(profile, writeMode)) .GatherResults()); }
static async Task TestStorage_Save(this IStorageService storageService, string fromBookmarkPath, string toBookmarkPath, FileWriteMode writeMode) { var fake = storageService.MakeFake(toBookmarkPath); var originBookmark = await storageService.Find(fromBookmarkPath); if (originBookmark == null) { throw new Exception($"Bookmark \"{fromBookmarkPath}\" does not exist!"); } if (await storageService.Save(new ProxyFilesGroup(fake, originBookmark), writeMode) == false) { throw new Exception($"{nameof(storageService.Save)} bookmark to \"{toBookmarkPath}\" was not successful!"); } PrintOutChangedDebugMessage(toBookmarkPath, toBookmarkPath); }
public abstract Task <bool> Save(FilesGroup filesGroup, FileWriteMode writeMode);
public Task <WriteResult> OverwriteTagsAsync(string srcPath, IEnumerable <Operation> updates, FileWriteMode writeMode) { VerifySourceFile(srcPath); VerifyUpdates(updates); var runner = new FileToFileRunner(_opts, srcPath, writeMode); return(runner.RunProcessAsync(updates)); }