public async Task SaveImage(Image image, Action <long, long?> report, Action <string> done) { var url = this.ImageEndpoint(image.DirectoryName, image.Name); var buffer = new byte[80 * 1024]; var read = 0; var index = 0l; var request = WebRequest.Create(url); var response = await request.GetResponseAsync(); try { using (var content = response.GetResponseStream()) { using (var target = File.OpenWrite($@"C:\temp\{image.Name}")) { while ((read = await content.ReadAsync(buffer, 0, buffer.Length, new System.Threading.CancellationToken())) > 0) { await target.WriteAsync(buffer, 0, read, new System.Threading.CancellationToken()); index += read; report(index, response.ContentLength); } } } done(null); } catch (Exception e) { done(e.Message); return; } }
public async Task <string> DownloadFileAsync(string fileName) { var fileId = Message.GetFileId(); if (fileId.IsNullOrEmpty()) { fileId = Message.ReplyToMessage.GetFileId(); } Log.Information($"Downloading file {fileId}"); var file = await Client.GetFileAsync(fileId) .ConfigureAwait(false); Log.Information($"DownloadFile: {file.ToJson(true)}"); fileName = $"Storage/Caches/{fileName}".EnsureDirectory(); using (var fileStream = File.OpenWrite(fileName)) { await Client.DownloadFileAsync(filePath : file.FilePath, destination : fileStream) .ConfigureAwait(false); Log.Information($"File saved to {fileName}"); } return(fileName); }
private async Task <(string filename, long length)> CopyFileToTempLocationAsync(IWebHostEnvironment env) { try { var file = Request.Form.Files.FirstOrDefault(); if (file != null) { var tmpFile = ReplaceInvalidFileNameChars ( $"{Path.GetFileNameWithoutExtension(file.FileName)}_{Guid.NewGuid():n}.tmp" ); var destinationFile = Path.Combine ( env.ContentRootPath, "Uploads", "Temp", tmpFile ); using var destinationStream = IOFile.OpenWrite(destinationFile); await file.CopyToAsync(destinationStream); return(destinationFile, file.Length); } } catch (Exception ex) { Trace.WriteLine(ex); } return(null, 0L); }
public async Task ReplaceFileAsync(IFile file, string contentType, Stream binary) { if (file == null) { throw new ArgumentNullException(nameof(file)); } if (string.IsNullOrEmpty(contentType)) { throw new ArgumentNullException(nameof(contentType)); } if (binary == null) { throw new ArgumentNullException(nameof(binary)); } var userId = _resolver.GetUserId(); if (userId == null) { throw new UnauthorizedAccessException(); } var _file = file as File; var path = ((File)file).BinaryPath; using (var stream = SysFile.OpenWrite(path)) { await binary.CopyToAsync(stream); } var size = new FileInfo(path).Length; await _files.UpdateMetaAsync(file.Id, contentType, size, userId, DateTimeOffset.UtcNow); }
private async Task SaveFromUrlAsync(string url, string fileName = null) { var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); string mediaType = response.Content.Headers.ContentType.MediaType; if (!IsAllowedType(mediaType)) { Info("Not support file type '{mimeType}' on '{url}'.", mediaType, url); return; } if (!EnsureFileSize(url, response.Content.Headers.ContentLength)) { return; } string filePath = GetFilePath(url, ref fileName); Info("Saving file '{fileName}'...", fileName); using (var fileContent = IoFile.OpenWrite(filePath)) await response.Content.CopyToAsync(fileContent); Info("Saving file '{fileName}' completed.", fileName); }
private static async Task LoopAsync(Client client, int period, string csvPath, CancellationToken cancellationToken) { var configuration = new CsvConfiguration(CultureInfo.InvariantCulture) { Delimiter = ";", ShouldQuote = (s, context) => true, IgnoreBlankLines = true, NewLine = NewLine.CRLF }; try { var delay = TimeSpan.FromMinutes(period); using (var stream = File.OpenWrite(csvPath)) using (var writer = new StreamWriter(stream, Encoding.UTF8)) using (var csvWriter = new CsvWriter(writer, configuration)) { csvWriter.WriteHeader <QueuedBuildStatus>(); while (true) { var now = DateTime.UtcNow; var result = await client.GetBuildsAsync(null, null, cancellationToken); await Task.WhenAll(WriteRecordsAsync(result, csvWriter, writer, now), Task.Delay(delay, cancellationToken)); } } } catch (OperationCanceledException) { // Ignore } }
static public void Save(Index <SoftFile> index, string filename) { using (FileStream file = FFile.OpenWrite(filename)) { SaveChild(index, file); } }
/// <summary> /// Downloads the file and save to file with the specified prefix name /// </summary> /// <param name="prefixName">The prefix name</param> /// <returns>The file name</returns> protected async Task <string> DownloadFileAsync(string prefixName) { var fileId = Message.GetFileId(); if (fileId.IsNullOrEmpty()) { fileId = Message.ReplyToMessage.GetFileId(); } Log.Information("Getting file by FileId {FileId}", fileId); var file = await Bot.GetFileAsync(fileId); var filePath = file.FilePath; Log.Debug("DownloadFile: {@File}", file); var fileName = $"{prefixName}_{filePath}"; fileName = $"Storage/Caches/{fileName}".EnsureDirectory(); await using var fileStream = SystemFile.OpenWrite(fileName); await Bot.DownloadFileAsync(file.FilePath, fileStream); Log.Information("File saved to {FileName}", fileName); return(fileName); }
/// <summary> /// provides a user dialog to load a csv file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Import_OnClick(object sender, RoutedEventArgs e) { var browser = new OpenFileDialog { Multiselect = false, Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*" }; // show browser browser.ShowDialog(); var fileName = browser.FileName; //Load CSV into Mainwindow if (AccProjectConfig.LoadBim360Projects(fileName)) { statusbar.Text = "Import successful!"; using (FileStream fs = File.OpenWrite(path_last)) { using (var sr = new StreamWriter(fs)) { //Delete the content of the file sr.Write(string.Empty); sr.WriteLine(fileName); } } } else { statusbar.Text = "Import failed! Unknown CSV Config or File not found!"; } }
async Task <long> JoinChunksAsync(string directory) { //folderName = Path.Combine(TempFolder, folderName); var fileName = Path.GetFileName(directory); fileName = Path.Combine(directory, $"{fileName}.tmp"); using (var outputStream = IOFile.OpenWrite(fileName)) { foreach (var tempFile in Directory.GetFiles(directory) .OrderBy(dir => dir) .Except(new[] { fileName })) { try { using (var inputStream = IOFile.OpenRead(tempFile)) await inputStream.CopyToAsync(outputStream); IOFile.Delete(tempFile); } catch { throw; } } return(outputStream.Length); } }
private static bool CanAccessFile(string file) { try { using (File.OpenWrite(file)) {} return(true); } catch (DirectoryNotFoundException) { return(true); } catch (FileNotFoundException) { return(true); } catch (IOException e) { // We expect this exception type to be thrown in case the file cannot be accessed because it's // still in use... Log.DebugFormat("Unable to access '{0}': {1}", file, e); return(false); } catch (Exception e) { Log.WarnFormat("Unable to access '{0}' for an unexpected reason: {1}", file, e); return(false); } }
private void Import_OnClick(object sender, RoutedEventArgs e) { //Folderbrowser var dialog = new CommonOpenFileDialog(); dialog.IsFolderPicker = false; dialog.Multiselect = false; //if use canceled the selection if (Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogResult.Cancel == dialog.ShowDialog()) { statusbar.Text = "canceled"; return; } //Load CSV into Mainwindow if (AccProjectConfig.LoadBim360Projects(dialog.FileName)) { statusbar.Text = "Import successful!"; using (FileStream fs = File.OpenWrite(path_last)) { using (var sr = new StreamWriter(fs)) { //Delete the content of the file sr.Write(string.Empty); sr.WriteLine(dialog.FileName); } } } else { statusbar.Text = "Import failed! Unknown CSV Config or File not found!"; } }
private void CompareWithMr(Table t) { string testFileName = Path.GetFullPath("temp.parquet"); if (F.Exists(testFileName)) { F.Delete(testFileName); } //produce file using (Stream s = F.OpenWrite(testFileName)) { using (var writer = new ParquetWriter(t.Schema, s)) { writer.Write(t); } } //read back Table t2 = ParquetReader.ReadTableFromFile(testFileName); //check we don't have a bug internally before launching MR Assert.Equal(t.ToString("j"), t2.ToString("j"), ignoreLineEndingDifferences: true); string mrJson = ExecAndGetOutput(_javaExecName, $"-jar {_toolsJarPath} cat -j {testFileName}"); Assert.Equal(t.ToString("j"), mrJson); }
/// <summary> /// Opens a <see cref="Stream" /> to write to a file. /// </summary> /// <param name="path">The path of the file.</param> /// <returns> /// A <see cref="Stream" /> that can write to a file. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> public Stream OpenWrite(string path) { _ = Requires.NotNullOrWhiteSpace( path, nameof(path)); return(FSFile.OpenWrite(path)); }
public void SaveSettingFile( ) { string config = Setting ? .Save( ); FileStream settingFile = File.OpenWrite(SettingFileName); StreamWriter writer = new StreamWriter(settingFile); writer.Write(config); writer.Dispose( ); }
public override Response Execute(Account account, Message message, Client client) { using (var stream = new MemoryStream()) { client.GetInfoAndDownloadFileAsync(message.Sticker.FileId, stream).Wait(); var image = Image.Load(stream); image.SaveAsPng(File.OpenWrite("sticker.png")); } return(new Response(new TextMessage(message.Chat, "some response"))); }
public async Task <IActionResult> PostAsync([FromForm] string key, IFormFile data) { if (string.IsNullOrEmpty(key)) { return(BadRequest("Key is empty")); } if (data == null) { return(BadRequest("Data is empty")); } SHA256 hashFunction = SHA256.Create(); string tempFileName = Path.GetTempFileName(); int bufferSize = 1024 * 1024; try { using (var dataStream = data.OpenReadStream()) using (var fs = IOFIle.OpenWrite(tempFileName)) { while (true) { byte[] buffer = new byte[bufferSize]; int bytesRead = await dataStream.ReadAsync(buffer, 0, buffer.Length); if (bytesRead <= 0) { break; } await fs.WriteAsync(buffer, 0, bytesRead); } } using (var fs = IOFIle.OpenRead(tempFileName)) { byte[] fileHash = hashFunction.ComputeHash(fs); fs.Position = 0; await cloudStorage.SaveFileAsync(key, fs); return(Ok(string.Join("", fileHash.Select(b => b.ToString("X2"))))); } } finally { if (IOFIle.Exists(tempFileName)) { IOFIle.Delete(tempFileName); } } }
public TypeScriptLanguageService() { #if DEBUG try { Directory.CreateDirectory(Path.GetDirectoryName(LogFilePath)); LogFileWriter = new StreamWriter(File.OpenWrite(LogFilePath)); } catch (IOException) // Maybe another instance is running. Anyway, this isn't really needed. { } #endif }
static void Main() { _dataDir = ConfigurationManager.AppSettings["TigreDataDirectory"]; _driveName = ConfigurationManager.AppSettings["DriveName"]; File.OpenWrite("./Log.txt").Close(); Directory.CreateDirectory("./Saved"); using (var control = new UsbControl()) { //Console.ReadLine(); Thread.Sleep(Timeout.Infinite); } }
public static FileStream OpenWrite(string path) { if (!DsFile.Exists(path)) { using (DsFile.Create(path)); } if (path != null && path.Length < 240) { return(System.IO.File.OpenWrite(path)); } return(MyFile.OpenWrite(path)); }
public override async Task <long> WriteAsync(string key, byte[] bytes, bool overwrite, CancellationToken cancellationToken) { var path = ComputePath(key); var directory = Path.GetDirectoryName(path); EnsureDirectoryExists(directory, true); //TODO : replace true by Create ??? using (var memoryStream = new MemoryStream(bytes, writable: false)) using (var fileStream = IOFile.OpenWrite(path)) await memoryStream.CopyToAsync(fileStream, cancellationToken); return(bytes.LongLength); }
public async Task CopyIfNeed(IFile file, string dir) { var path = Path.Combine(dir, file.Name); if (NeedCopy(file, path)) { using (var dst = SysFile.OpenWrite(Path.Combine(path))) using (var src = _storage.OpenFile(file)) { await src.CopyToAsync(dst); } } }
/// <summary> /// Initialise the file persistence /// </summary> /// <param name="fileName">The filename to save to</param> /// <param name="loadExisting"></param> public bool Initialise(string fileName, bool loadExisting) { return(HandleFileAccess(() => { _fileName = fileName; if (loadExisting && File.Exists(fileName)) { LoadCoverageFile(); } // test the file location can be accessed using (var fs = File.OpenWrite(fileName)) fs.Close(); }, fileName)); }
private async void lblClearIconCache_Click(object sender, EventArgs e) { cmbbxServer.Enabled = false; btnConnect.Enabled = false; lblClearIconCache.Enabled = false; lblCreateShortcut.Hide(); tbcntrlMain.SelectedIndex = 0; lblCurrentServer.Text = "Clearing cache..."; Application.DoEvents(); Directory.Delete(m_iconCacheFolder, true); Directory.CreateDirectory(m_iconCacheFolder); m_servers.ForEach(x => x.Icon = null); // Check for servers which icons arent in cache yet foreach (Server server in m_servers) { lblCurrentServer.Text = $"Downloading icon of {server.ServerName}..."; Application.DoEvents(); Image icon = await DownloadImageAsync(server.IconUrl); icon.Save(m_iconCacheFolder + $@"\{server.ServerName}.png"); icon.Dispose(); } // Load icons from cache foreach (Server server in m_servers) { if (File.Exists(m_iconCacheFolder + $@"\{server.ServerName}.png")) { using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(m_iconCacheFolder + $@"\{server.ServerName}.png"))) server.Icon = Image.FromStream(ms); } } // Create .ico files for shortcuts foreach (Server server in m_servers) { using (FileStream fs = File.OpenWrite(m_iconCacheFolder + $@"\{server.ServerName}.ico")) using (MemoryStream ms = new MemoryStream((byte[])new ImageConverter().ConvertTo(server.Icon, typeof(byte[])))) ImagingHelper.ConvertToIcon(ms, fs, 48, true); } cmbbxServer.Enabled = true; btnConnect.Enabled = true; lblClearIconCache.Enabled = true; lblCreateShortcut.Show(); UpdateServerUI(); }
public async Task <IActionResult> UploadLinq(IFormFile uploadedFile) { if (!uploadedFile.FileName.EndsWith(".linq")) { return(BadRequest("File extension need be .linq")); } string directory = EnsureDirectory(Path.GetFileNameWithoutExtension(uploadedFile.FileName)); using (FileStream file = SystemFile.OpenWrite(Path.Combine(directory, "Runner.linq"))) using (Stream destStream = uploadedFile.OpenReadStream()) { await destStream.CopyToAsync(file); } return(Ok()); }
public void Download(string fileId, string targetLocalPath) { CoreContext.TenantManager.SetCurrentTenant(tenantId); using (var fileDao = GetFileDao()) { var file = fileDao.GetFile(fileId); if (file == null) { throw new FileNotFoundException("File not found."); } using (var source = fileDao.GetFileStream(file)) using (var destination = IoFile.OpenWrite(targetLocalPath)) { source.CopyTo(destination); } } }
public string SaveDocument([FromBody] string documentText) { // by arbitrary standard, first line is guid, and rest is body of text string id = documentText.Substring(0, documentText.IndexOf('\n')); // TODO check if id is valid incase someone tries to mess with the api string text = documentText.Substring(documentText.IndexOf('\n') + 1); // write to the existing document string filename = "Documents/" + GenerateHash(id) + ".md"; using (FileStream fs = SystemFile.OpenWrite(filename)) using (StreamWriter sw = new StreamWriter(fs)) { sw.Write(text); } return(id); }
public async Task <IFile> AddFileAsync(IFolder folder, string name, string contentType, Stream binary) { if (folder == null) { throw new ArgumentNullException(nameof(folder)); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException(nameof(name)); } if (name.Contains("/")) { throw new ArgumentException("Cannot use path delimiter('/')", nameof(name)); } if (string.IsNullOrEmpty(contentType)) { throw new ArgumentNullException(nameof(contentType)); } if (binary == null) { throw new ArgumentNullException(nameof(binary)); } var userId = _resolver.GetUserId(); if (userId == null) { throw new UnauthorizedAccessException(); } var path = CreateBinaryPath(); using (var stream = SysFile.OpenWrite(path)) { await binary.CopyToAsync(stream); } var size = new FileInfo(path).Length; var file = await _files.AddAsync(folder.Id, name, path, contentType, size, userId, DateTimeOffset.UtcNow); return(Mapping.Mapper.Map <File>(file)); }
public async Task <IActionResult> Upload(IFormFile file) { if (F.Exists(file.FileName)) { F.Delete(file.FileName); } await file.CopyToAsync(F.OpenWrite(file.FileName)); if (Path.GetExtension(file.FileName) == "db") { using (var conn = new SQLiteConnection(file.FileName)) { conn.Execute("SELECT COUNT(*) FROM sqlite_master WHERE type='table'"); } } // TODO: with resume offset return(this.Ok()); }
static void CompressNew(string src, string dest) { using (FileStream streamDest = F.OpenWrite(dest)) { using (Stream streamSnappy = IronSnappy.Snappy.OpenWriter(streamDest)) { using (FileStream streamSrc = F.OpenRead(src)) { using (var time = new TimeMeasure()) { streamSrc.CopyTo(streamSnappy); TimeSpan duration = time.Elapsed; Console.WriteLine($"new: {src} => {dest}. {duration} {new FileInfo(dest).Length}"); } } } } }