public static async Task WriteStreamAsync(string path, Stream contents) { using (var writer = File.Create(path)) { await contents.CopyToAsync(writer).ConfigureAwait(false); } }
public static async Task SendAsync(this HttpWebRequest request, Stream input) { using (var stream = await request.GetRequestStreamAsync()) { await input.CopyToAsync(stream); } }
public async Task SaveFile(string name, Stream stream) { var fullPath = GetFullPath(name); using (var fs = new FileStream(fullPath, FileMode.OpenOrCreate, FileAccess.Write)) { await stream.CopyToAsync(fs).ConfigureAwait(false); await stream.FlushAsync().ConfigureAwait(false); await fs.FlushAsync().ConfigureAwait(false); } }
private async Task ComputeOtherSizesAsync(Entry entry, Image image, Stream originalContent, bool canSeek) { if (!canSeek) { var memoryStream = new MemoryStream(); await originalContent.CopyToAsync(memoryStream); await originalContent.DisposeAsync(); originalContent = memoryStream; originalContent.Position = 0; canSeek = true; } using (var thumbnailContent = new MemoryStream()) using (var originalCopy = new MemoryStream()) { await originalContent.CopyToAsync(originalCopy); originalCopy.Position = 0; resizeService.Thumbnail(originalCopy, thumbnailContent, ThumbnailWidth, ThumbnailHeight); thumbnailContent.Position = 0; await fileStorage.SaveAsync(entry, image, thumbnailContent, ImageType.Thumbnail); } if (canSeek) { originalContent.Position = 0; } else { originalContent = await fileStorage.FindAsync(entry, image, ImageType.Original); } using (var previewContent = new MemoryStream()) using (var originalCopy = new MemoryStream()) { await originalContent.CopyToAsync(originalCopy); originalCopy.Position = 0; resizeService.Resize(originalCopy, previewContent, PreviewWidth); previewContent.Position = 0; await fileStorage.SaveAsync(entry, image, previewContent, ImageType.Preview); } }
public async Task<byte[]> CopyStreamToByteBuffer(Stream stream) { var memoryStream = new MemoryStream(); await stream.CopyToAsync(memoryStream); return memoryStream.ToArray(); }
public async Task<UploadDto> UploadFile(string fileName, string contentType, Stream stream) { var uploadDirectoryPath = Path.Combine(hostingEnvironment.WebRootPath, settings.LocalFileSystemStoragePath); string randomFile = Path.GetFileNameWithoutExtension(fileName) + "_" + Guid.NewGuid().ToString().Substring(0, 4) + Path.GetExtension(fileName); if (!Directory.Exists(uploadDirectoryPath)) { Directory.CreateDirectory(uploadDirectoryPath); } var targetFile = Path.GetFullPath(Path.Combine(uploadDirectoryPath, randomFile)); using (var destinationStream = File.Create(targetFile)) { await stream.CopyToAsync(destinationStream); } var result = new UploadDto { FileExtn = Path.GetExtension(fileName), FileName = fileName, Url = GetFullUrl(settings.LocalFileSystemStorageUriPrefix, randomFile) }; return result; }
public async Task AddFileAsync(string outputPath, Stream sourceStream) { using (var writeStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) { await sourceStream.CopyToAsync(writeStream); } }
public static async Task<IRandomAccessStream> ConvertToRandomAccessStream(Stream source) { Stream streamToConvert = null; if (!source.CanRead) throw new Exception("The source cannot be read."); if (!source.CanSeek) { var memStream = new MemoryStream(); await source.CopyToAsync(memStream); streamToConvert = memStream; } else { streamToConvert = source; } var reader = new DataReader(streamToConvert.AsInputStream()); streamToConvert.Position = 0; await reader.LoadAsync((uint) streamToConvert.Length); var buffer = reader.ReadBuffer((uint) streamToConvert.Length); var randomAccessStream = new InMemoryRandomAccessStream(); var outputStream = randomAccessStream.GetOutputStreamAt(0); await outputStream.WriteAsync(buffer); await outputStream.FlushAsync(); return randomAccessStream; }
internal static Bitmap FromStream(Stream stream) { Bitmap bitmap = null; Task.Run(async () => { using (var raStream = new InMemoryRandomAccessStream()) { await stream.CopyToAsync(raStream.AsStream()); var decoder = await BitmapDecoder.CreateAsync(raStream); var pixelData = await decoder.GetPixelDataAsync(); var width = (int)decoder.OrientedPixelWidth; var height = (int)decoder.OrientedPixelHeight; const PixelFormat format = PixelFormat.Format32bppArgb; var bytes = pixelData.DetachPixelData(); bitmap = new Bitmap(width, height, format); var data = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, format); Marshal.Copy(bytes, 0, data.Scan0, bytes.Length); bitmap.UnlockBits(data); } }).Wait(); return bitmap; }
public static async Task<Stream> CompressAsync(CompressionType type, Stream original) { using (var ms = new MemoryStream()) { Stream compressedStream = null; if (type == CompressionType.deflate) { compressedStream = new DeflateStream(ms, CompressionMode.Compress); } else if (type == CompressionType.gzip) { compressedStream = new GZipStream(ms, CompressionMode.Compress); } if (type != CompressionType.none) { using (compressedStream) { await original.CopyToAsync(compressedStream); } //NOTE: If we just try to return the ms instance, it will simply not work // a new stream needs to be returned that contains the compressed bytes. // I've tried every combo and this appears to be the only thing that works. byte[] output = ms.ToArray(); return new MemoryStream(ms.ToArray()); } //not compressed return original; } }
public async Task<ResizeResult> Resize(string fileName, Stream stream) { string wwwroot = this.env.WebRootPath; string folderpath = Path.Combine(wwwroot, "dl"); if (!this.fileSystemHelper.isDirectoryExists(folderpath)) { this.fileSystemHelper.CreateDirectory(folderpath); } string filePath = Path.Combine(folderpath, fileName); using (var fs = this.fileSystemHelper.CreateFile(filePath)) { await stream.CopyToAsync(fs); } string rawUri = string.Format(CultureInfo.InvariantCulture, "{0}://{1}/dl/{2}", this.httpContextAccessor.HttpContext.Request.Scheme, this.httpContextAccessor.HttpContext.Request.Host, fileName); return new ResizeResult() { UriActualSize = rawUri, UriResizedSize = await this.resizer.Resize(rawUri, Constants.MaxHeight, Constants.MaxWide) }; }
internal static async Task ProcessContentStream(Stream contentStream, Dictionary<string, List<string>> options) { if (contentStream != null) { string fileName = options.ContainsKey(Constants.FILE) ? options[Constants.FILE][0] : null; if (fileName != null) { using (Stream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None, 1012 * 1024, true)) { await contentStream.CopyToAsync(stream); Console.WriteLine("The partstudio has been downloaded to {0}", fileName); } } else { long bufferLength = (contentStream.Length > Constants.MAX_FILE_LENGTH_TO_PRINT_OUT) ? Constants.MAX_FILE_LENGTH_TO_PRINT_OUT : contentStream.Length; byte[] buffer = new byte[bufferLength]; contentStream.Read(buffer, 0, (int)contentStream.Length); Console.WriteLine(Encoding.ASCII.GetString(buffer)); if (contentStream.Length > Constants.MAX_FILE_LENGTH_TO_PRINT_OUT) { Console.WriteLine("..."); } } } else { Console.WriteLine("Download failed"); } }
public async Task AddAsync(MobileServiceFile file, Stream source) { using (var target = await this.fileSystem.CreateAsync(GetFileName(file))) { await source.CopyToAsync(target); } }
/// <exception cref="System.ArgumentException">Stream \data\ must be readable.;data</exception> /// <inheritdoc /> public virtual async Task<byte[]> ComputeHashAsync(Stream data) { if (!data.CanRead) throw new ArgumentException("Stream \"data\" must be readable.", "data"); if (!data.CanSeek && RequiresSeekableStream) { byte[] buffer; using (var ms = new MemoryStream()) { await data.CopyToAsync(ms) .ConfigureAwait(false); buffer = ms.ToArray(); } // Use non-async because all of the data is in-memory return ComputeHashInternal( new ArrayData(buffer)); } return await ComputeHashAsyncInternal(new StreamData(data)) .ConfigureAwait(false); }
/// <summary> /// /// </summary> /// <param name="inputStream"></param> /// <param name="sourcefilename"></param> /// <param name="containerName"></param> /// <param name="destpath"></param> /// <param name="useUUIDName"></param> /// <param name="overwrite"></param> /// <param name="useSequencedName"></param> /// <returns></returns> public async Task <UploadedInfo> UploadAsync(System.IO.Stream inputStream, string sourcefilename, string containerName, string destpath = "", bool useUUIDName = true, bool overwrite = false, bool useSequencedName = true) { do { try { string relativeFilePath = GetDestFilePath(sourcefilename, containerName, destpath, useUUIDName, overwrite, useSequencedName); InitDirectory(Path.Combine(RootPath, relativeFilePath)); string fileFullPath = Path.Combine(RootPath, relativeFilePath); using (var fileStream = File.Create(fileFullPath)) { inputStream.Seek(0, SeekOrigin.Begin); await inputStream.CopyToAsync(fileStream); } var fileInfo = new FileInfo(fileFullPath); Uri url = new Uri(PublicRootUrl + "/" + relativeFilePath); return(new UploadedInfo { AbsoluteUri = url.AbsoluteUri, Length = fileInfo.Length }); } catch (Exception ex) { if (typeof(DuplicateFileException) == ex.GetType()) { throw ex; } } } while (--retryCount > 0); throw new OutOfReTryCountException(); }
public async Task<UploadResult> UploadFile(string fileName, string contentType, Stream stream) { ApplicationSettings settings = _settingsFunc(); // Randomize the filename everytime so we don't overwrite files string randomFile = Path.GetFileNameWithoutExtension(fileName) + "_" + Guid.NewGuid().ToString().Substring(0, 4) + Path.GetExtension(fileName); if (!Directory.Exists(settings.LocalFileSystemStoragePath)) { Directory.CreateDirectory(settings.LocalFileSystemStoragePath); } // REVIEW: Do we need to validate the settings here out of paranoia? string targetFile = Path.GetFullPath(Path.Combine(settings.LocalFileSystemStoragePath, randomFile)); using (FileStream destinationStream = File.Create(targetFile)) { await stream.CopyToAsync(destinationStream); } var result = new UploadResult { Url = GetFullUrl(settings.LocalFileSystemStorageUriPrefix, randomFile), Identifier = randomFile }; return result; }
public static async Task SendAsync(this HttpWebRequest request, Stream input, CancellationToken cancellationToken) { using (var stream = await request.GetRequestStreamAsync()) { await input.CopyToAsync(stream, cancellationToken); } }
public async Task<string> Put(Stream stream, TimeSpan timeToBeReceived) { using (FileStream destination = File.OpenWrite("blob.dat")) { await stream.CopyToAsync(destination); } return "the-key-of-the-stored-file-such-as-the-full-path"; }
public async Task StoreAsync(string path, Stream stream) { using (var ms = new MemoryStream()) { await stream.CopyToAsync(ms); _files[path] = ms.ToArray(); } }
private async Task<byte[]> ReadAllBytesAsync(Stream stream) { using (var memoryStream = new MemoryStream()) { await stream.CopyToAsync(memoryStream); return memoryStream.ToArray(); } }
internal static async Task InstallFromStream(Stream stream, Library library, string packagesDirectory, SHA512 sha512) { var packagePathResolver = new DefaultPackagePathResolver(packagesDirectory); var targetPath = packagePathResolver.GetInstallPath(library.Name, library.Version); var targetNuspec = packagePathResolver.GetManifestFilePath(library.Name, library.Version); var targetNupkg = packagePathResolver.GetPackageFilePath(library.Name, library.Version); var hashPath = packagePathResolver.GetHashPath(library.Name, library.Version); // Acquire the lock on a nukpg before we extract it to prevent the race condition when multiple // processes are extracting to the same destination simultaneously await ConcurrencyUtilities.ExecuteWithFileLocked(targetNupkg, async createdNewLock => { // If this is the first process trying to install the target nupkg, go ahead // After this process successfully installs the package, all other processes // waiting on this lock don't need to install it again if (createdNewLock) { Directory.CreateDirectory(targetPath); using (var nupkgStream = new FileStream(targetNupkg, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete)) { await stream.CopyToAsync(nupkgStream); nupkgStream.Seek(0, SeekOrigin.Begin); ExtractPackage(targetPath, nupkgStream); } // Fixup the casing of the nuspec on disk to match what we expect var nuspecFile = Directory.EnumerateFiles(targetPath, "*" + NuGet.Constants.ManifestExtension).Single(); if (!string.Equals(nuspecFile, targetNuspec, StringComparison.Ordinal)) { Manifest manifest = null; using (var nuspecStream = File.OpenRead(nuspecFile)) { manifest = Manifest.ReadFrom(nuspecStream, validateSchema: false); manifest.Metadata.Id = library.Name; } // Delete the previous nuspec file File.Delete(nuspecFile); // Write the new manifest using (var targetNuspecStream = File.OpenWrite(targetNuspec)) { manifest.Save(targetNuspecStream); } } stream.Seek(0, SeekOrigin.Begin); var nupkgSHA = Convert.ToBase64String(sha512.ComputeHash(stream)); File.WriteAllText(hashPath, nupkgSHA); } return 0; }); }
public async Task AddAsync(string key, IO.Stream stream) { string tempFile = IO.Path.Combine(temporaryDirectory, Guid.NewGuid().ToString()); IO.FileStream fileStream = new IO.FileStream(tempFile, IO.FileMode.CreateNew); await stream.CopyToAsync(fileStream); Add(key, tempFile); }
public async Task SaveAsync(string path, Stream file) { var localpath = HttpContext.Current.Server.MapPath("~/" + path); using (var localFileStream = new FileStream(localpath, FileMode.Create, FileAccess.Write)) { file.Seek(0, SeekOrigin.Begin); await file.CopyToAsync(localFileStream); } }
/// <summary> /// Stores uploaded file and returns its unique id. /// </summary> public async Task<Guid> StoreFile(Stream stream) { var id = Guid.NewGuid(); using (var fs = new FileStream(GetFileName(id), FileMode.OpenOrCreate, FileAccess.Write)) { await stream.CopyToAsync(fs); } return id; }
/// <summary> /// Convert stream to byte data /// </summary> /// <param name="source"></param> /// <returns></returns> public static async Task <byte[]> ConvertStreamToBytes(this System.IO.Stream source) { using (var ms = new MemoryStream()) { await source.CopyToAsync(ms); return(ms.ToArray()); } }
private static async Task<IBuffer> CreateBuffer(Stream stream) { MemoryStream memoryStream; using (memoryStream = new MemoryStream()) { await stream.CopyToAsync(memoryStream).ConfigureAwait(false); return CryptographicBuffer.CreateFromByteArray(MemoryStreamToArrayFast(memoryStream)); } }
protected static async Task<byte[]> LoadHgtDataFromStreamAsync(Stream zipStream) { byte[] hgtData; using (var memory = new MemoryStream()) { await zipStream.CopyToAsync(memory); hgtData = memory.ToArray(); } return hgtData; }
/// <summary> /// Loads endpoint information including private data from the specified stream. /// </summary> /// <param name="stream">A stream, previously serialized to using <see cref="SaveAsync"/>.</param> /// <returns>A task whose result is the deserialized instance of <see cref="OwnEndpoint"/>.</returns> public static async Task<OwnEndpoint> OpenAsync(Stream stream) { Requires.NotNull(stream, "stream"); var ms = new MemoryStream(); await stream.CopyToAsync(ms); // relies on the input stream containing only the endpoint. ms.Position = 0; using (var reader = new BinaryReader(ms)) { return reader.DeserializeDataContract<OwnEndpoint>(); } }
protected static Task SendStreamAsync(Stream from, Stream to, CancellationToken cancellationToken) { return from.CopyToAsync(to, CopyBufferSize, cancellationToken) .ContinueWith( task => { from.Close(); task.Wait(cancellationToken); }, TaskContinuationOptions.ExecuteSynchronously); }
public async Task WriteStreamToFileAsync(Stream dataStream, string fileName, string folderName = null) { // Ensure crashes folder exists if (!isoStore.DirectoryExists(folderName)) { isoStore.CreateDirectory(folderName); } using (var fileStream = isoStore.OpenFile((folderName ?? "") + Path.DirectorySeparatorChar + fileName,FileMode.Create,FileAccess.Write)) { await dataStream.CopyToAsync(fileStream); } }
public async Task WriteStreamToFileAsync(System.IO.Stream dataStream, string fileName, string folderName = null) { var folder = await folderName.GetLocalFolderByNameCreateIfNotExistingAsync(); var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using (var stream = await file.OpenStreamForWriteAsync()) { await dataStream.CopyToAsync(stream); } }
// TODO GATH: How to deal with Filesystem related topics? PCLStorage? public static async Task<StorageFile> SaveToLocalFolderAsync(Stream stream, string fileName) { StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using (Stream outputStream = await storageFile.OpenStreamForWriteAsync()) { await stream.CopyToAsync(outputStream); } return storageFile; }
public async Task WriteStreamToFileAsync(Stream dataStream, string fileName, string folderName = null) { StorageFolder localFolder = ApplicationData.Current.LocalFolder; if (folderName != null) { localFolder = await localFolder.CreateFolderAsync(folderName,CreationCollisionOption.OpenIfExists); } using(var stream = await localFolder.OpenStreamForWriteAsync(fileName, CreationCollisionOption.ReplaceExisting)){ await dataStream.CopyToAsync(stream); } }
public async Task <string> StoreAsync(System.IO.Stream fileStream, string extension) { var fileName = Guid.NewGuid().ToString() + extension; using (var newFileStream = System.IO.File.OpenWrite(settings.FilesBasePath + fileName)) { await fileStream.CopyToAsync(newFileStream); await newFileStream.FlushAsync(); } return(fileName); }
public async Task <FileUploadResult> HandleUpload(string fileName, System.IO.Stream stream) { string uuid = GetFileName(); string targetFile = GetTargetFile(uuid); using (FileStream destinationStream = File.Create(targetFile + ".png")) { await stream.CopyToAsync(destinationStream); } return(new FileUploadResult() { Identifier = uuid }); }
/// <summary> /// Write the media stream to the specified path. /// </summary> public void Download(string path) { CSTube.Log(string.Format("Downloading File to {0}", path)); Directory.CreateDirectory(Path.GetDirectoryName(path)); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(URL); using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { CSTube.Log(string.Format("Total file size in bytes: {0}", response.Headers["content-length"])); using (System.IO.Stream input = response.GetResponseStream()) using (System.IO.Stream output = File.OpenWrite(path)) input.CopyToAsync(output).Wait(); } }
public async Task SaveStream(string fileName, System.IO.Stream stream) { var _lock = XNamedLock.Get(fileName); using (var releaser = await _lock.LockAsync()) { var path = _getPath(fileName); _createDirForFile(path); using (var s = File.Create(path)) { await stream.CopyToAsync(s); } } }
public async Task SavePdfAsync() { const string url = "https://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf"; using (HttpClient client = _httpClientFactory.CreateClient()) { using (HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead)) using (System.IO.Stream streamToReadFrom = await response.Content.ReadAsStreamAsync()) { string fileToWriteTo = Path.GetTempFileName(); using (System.IO.Stream streamToWriteTo = File.Open(fileToWriteTo, FileMode.Create)) { await streamToReadFrom.CopyToAsync(streamToWriteTo); } } } }
/// <summary> /// Load list of files in SharePoint folder and then downloads each file to 'Files' folder nex to the exe. /// Example of first argument: folder/another subfolder/and so on /// </summary> /// <param name="args">List relative URL to the folder</param> /// <returns>Task</returns> static async Task Main(string[] args) { if (!IsConfigAndArgumentsValid(args)) { Console.WriteLine("Missing argument with folder URL or configuration values in app settings."); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); return; } string folder = args[0]; using (ClientContext client = await AuthenticationUtilities.GetClientContextAsync(Config.SiteUrl)) using (SecureString password = new SecureString()) { Console.WriteLine("Connecting to SharePoint site..."); client.Load(client.Web, w => w.ServerRelativeUrl); await client.ExecuteQueryAsync(); Console.WriteLine("Loading files list..."); var files = await GetFilesFromFolderAsync(client, folder); Console.WriteLine($"Loaded {files.Count()} files"); IO.Directory.CreateDirectory("Files"); foreach (SPFileInfo fileInfo in files) { Console.Write($"Downloading file '{fileInfo.FileName}' ... "); using (IO.Stream stream = await DownloadFileAsync(client, fileInfo.ServerRelativeUrl)) using (IO.FileStream file = IO.File.Create($@"Files\{fileInfo.FileName}")) { await stream.CopyToAsync(file); Console.WriteLine("OK"); } } } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); }
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { return(_innerStream.CopyToAsync(destination, bufferSize, cancellationToken)); }
/// <returns>Success</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task <string> DownloadJobFileResultAsync(string filename, string jobId, System.Threading.CancellationToken cancellationToken, string fileToWriteTo) { string outputFile = ""; var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/DownloadJobFileResult"); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var boundary_ = System.Guid.NewGuid().ToString(); var content_ = new System.Net.Http.MultipartFormDataContent(boundary_); content_.Headers.Remove("Content-Type"); content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_); if (filename != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(filename, System.Globalization.CultureInfo.InvariantCulture)), "filename"); } if (jobId != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(jobId, System.Globalization.CultureInfo.InvariantCulture)), "jobId"); } request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/octet-stream")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); using (System.IO.Stream streamToReadFrom = await response_.Content.ReadAsStreamAsync()) { outputFile = response_.Content.Headers.ContentDisposition.FileName; using (Stream streamToWriteTo = File.Open(Path.Combine(fileToWriteTo, outputFile), FileMode.Create)) { await streamToReadFrom.CopyToAsync(streamToWriteTo); } } var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200" || status_ == "206") { var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false); var fileResponse_ = new FileResponse((int)response_.StatusCode, headers_, responseStream_, null, response_); client_ = null; response_ = null; // response and client are disposed by FileResponse return(outputFile); } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } return(outputFile); }
/// <summary> /// Serialize the HTTP content to a stream as an asynchronous operation. /// </summary> /// <param name="stream">The target stream.</param> /// <param name="context">Information about the transport (channel binding token, for example). This /// parameter may be null.</param> /// <returns> /// Returns System.Threading.Tasks.Task.The task object representing the asynchronous /// operation. /// </returns> protected override Task SerializeToStreamAsync(Stream stream, System.Net.TransportContext context) { return(m_stream.CopyToAsync(stream)); }
public static async Task <global::Android.Net.Uri> OnImagePickerResult([GeneratedEnum] Result resultCode, Intent data, global::Android.Net.Uri outputFileUri, Context context, string finalPath, int largeSide, int shortSide) { bool isCamera; global::Android.Net.Uri selectedImage; if (data == null || data.Data == null) { isCamera = true; } else { string action = data.Action; if (action == null) { isCamera = false; } else { isCamera = action == MediaStore.ActionImageCapture; } } if (isCamera) { selectedImage = outputFileUri; } else { selectedImage = (data == null) ? null : data.Data; if (selectedImage != null) { System.IO.Stream stream = context.ContentResolver.OpenInputStream(selectedImage); if (File.Exists(outputFileUri.Path)) { File.Delete(outputFileUri.Path); } using (var fileStream = File.Create(outputFileUri.Path)) { await stream.CopyToAsync(fileStream); selectedImage = outputFileUri; } } } if (selectedImage == null || !File.Exists(selectedImage.Path)) { return(null); } // Scale the image down to a maximum size Bitmap fullBitmap = await BitmapFactory.DecodeFileAsync(selectedImage.Path); int currentSize = fullBitmap.Width * fullBitmap.Height; int maxSize = largeSide * shortSide; if (currentSize <= maxSize) { // Small enough, save without resizing await WriteBitmapToFile(finalPath, fullBitmap); } else { float scale = (float)maxSize / (float)currentSize; // CREATE A MATRIX FOR THE MANIPULATION Matrix matrix = new Matrix(); // RESIZE THE BIT MAP matrix.PostScale(scale, scale); // "RECREATE" THE NEW BITMAP Bitmap resizedBitmap = Bitmap.CreateBitmap( fullBitmap, 0, 0, fullBitmap.Width, fullBitmap.Height, matrix, false); fullBitmap.Recycle(); await WriteBitmapToFile(finalPath, resizedBitmap); } File.Delete(selectedImage.Path); Java.IO.File newFile = new Java.IO.File(finalPath); return(global::Android.Net.Uri.FromFile(newFile)); }
static async Task PlatformSaveAsync(MediaFileType type, Stream fileStream, string fileName) { var albumName = AppInfo.Name; var context = Platform.AppActivity; var dateTimeNow = DateTime.Now; var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); var extension = Path.GetExtension(fileName).ToLower(); var newFileName = $"{fileNameWithoutExtension}_{dateTimeNow:yyyyMMdd_HHmmss}{extension}"; using var values = new ContentValues(); values.Put(MediaColumns.DateAdded, TimeSeconds(dateTimeNow)); values.Put(MediaColumns.Title, fileNameWithoutExtension); values.Put(MediaColumns.DisplayName, newFileName); var mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension.Replace(".", string.Empty)); if (!string.IsNullOrWhiteSpace(mimeType)) { values.Put(MediaColumns.MimeType, mimeType); } using var externalContentUri = type == MediaFileType.Image ? MediaStore.Images.Media.ExternalContentUri : MediaStore.Video.Media.ExternalContentUri; var relativePath = type == MediaFileType.Image ? Environment.DirectoryPictures : Environment.DirectoryMovies; if ((int)Build.VERSION.SdkInt >= 29) { values.Put(MediaColumns.RelativePath, Path.Combine(relativePath, albumName)); values.Put(MediaColumns.IsPending, true); using var uri = context.ContentResolver.Insert(externalContentUri, values); using var stream = context.ContentResolver.OpenOutputStream(uri); await fileStream.CopyToAsync(stream); stream.Close(); values.Put(MediaColumns.IsPending, false); context.ContentResolver.Update(uri, values, null, null); } else { #pragma warning disable CS0618 // Type or member is obsolete using var directory = new File(Environment.GetExternalStoragePublicDirectory(relativePath), albumName); directory.Mkdirs(); using var file = new File(directory, newFileName); using var fileOutputStream = System.IO.File.Create(file.AbsolutePath); await fileStream.CopyToAsync(fileOutputStream); fileOutputStream.Close(); values.Put(MediaColumns.Data, file.AbsolutePath); context.ContentResolver.Insert(externalContentUri, values); using var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile); mediaScanIntent.SetData(Uri.FromFile(file)); context.SendBroadcast(mediaScanIntent); #pragma warning restore CS0618 // Type or member is obsolete } }
public async Task SendDataAsync(System.IO.Stream stream) { await stream.CopyToAsync(NetworkStream); }
public OpenAlAsyncLoadSound(int source, bool looping, bool relative, Vector3 pos, float volume, int channels, int sampleBits, int sampleRate, System.IO.Stream stream) : base(source, looping, relative, pos, volume, sampleRate) { var silentSource = new OpenAlSoundSource(SilentDta, channels, sampleBits, sampleRate); AL.Source(source, ALSourcei.Buffer, (int)silentSource.Buffer); playTask = Task.Run(async() => { System.IO.MemoryStream memoryStream; using (stream) { memoryStream = new MemoryStream(); try { await stream.CopyToAsync(memoryStream, 81920, cts.Token); } catch (TaskCanceledException) { AL.SourceStop(source); AL.Source(source, ALSourcei.Buffer, 0); silentSource.Dispose(); return; } } var data = memoryStream.ToArray(); var bytesPerSample = sampleBits / 8f; var lengthInSecs = data.Length / (channels * bytesPerSample * sampleRate); using (var soundSource = new OpenAlSoundSource(data, channels, sampleBits, sampleRate)) { AL.SourceStop(source); AL.Source(source, ALSourcei.Buffer, (int)soundSource.Buffer); silentSource.Dispose(); lock (cts) { if (!cts.IsCancellationRequested) { int state; AL.GetSource(Source, ALGetSourcei.SourceState, out state); if (state != (int)ALSourceState.Stopped) { AL.SourcePlay(source); } else { AL.SourceRewind((uint)source); } } } while (!cts.IsCancellationRequested) { var currentSeek = SeekPosition; int state; AL.GetSource(Source, ALGetSourcei.SourceState, out state); if (state == (int)ALSourceState.Stopped) { break; } try { var delaySecs = Math.Max(lengthInSecs - currentSeek, 1 / 60f); await Task.Delay(TimeSpan.FromSeconds(delaySecs), cts.Token); } catch (TaskCanceledException) { } } AL.Source(Source, ALSourcei.Buffer, 0); } }); }
/// <summary> /// Saves the binary data available in the stream in the /// given media object. /// </summary> /// <param name="media">The media object</param> /// <param name="stream">The stream</param> public async void Put(Models.Media media, Stream stream) { if (!disabled) { using (var writer = new FileStream(Path.Combine(mediaMapped, media.Id.ToString()), FileMode.Create)) { await stream.CopyToAsync(writer); } } }
/// <summary> /// Issues the web request asynchronous. /// </summary> /// <param name="endpoint">The endpoint.</param> /// <param name="method">The method.</param> /// <param name="input">The input.</param> /// <param name="alternativeEndpointBase">The alternative endpoint base.</param> /// <returns></returns> public async Task<HttpWebResponse> IssueWebRequestAsync( string endpoint, string method = "GET", Stream input = null, string alternativeEndpointBase = null) { string baseEndPoint = alternativeEndpointBase ?? (Constants.UseRestEndpointBase ? Constants.RestEndpointBase : string.Empty); HttpWebRequest httpWebRequest = WebRequest.CreateHttp(new Uri(_credentials.ClusterUri, baseEndPoint + endpoint)); httpWebRequest.PreAuthenticate = false; httpWebRequest.Method = method; if (!string.IsNullOrWhiteSpace(endpoint) && !endpoint.Contains("version/cluster")) { httpWebRequest.Accept = _contentType; httpWebRequest.ContentType = _contentType; } if (input != null) { // seek to the beginning, so we copy everything in this buffer input.Seek(0, SeekOrigin.Begin); using (Stream req = httpWebRequest.GetRequestStream()) { await input.CopyToAsync(req); } } return (await httpWebRequest.GetResponseAsync()) as HttpWebResponse; }