public WriteAsync ( byte buffer, int offset, int count, CancellationToken cancellationToken ) : Task | ||
buffer | byte | |
offset | int | |
count | int | |
cancellationToken | CancellationToken | |
return | Task |
public void NegativeOffsetThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { Assert.Throws<ArgumentOutOfRangeException>("offset", () => FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], -1, 1))); // buffer is checked first Assert.Throws<ArgumentNullException>("buffer", () => FSAssert.CompletesSynchronously(fs.WriteAsync(null, -1, 1))); } }
public static async Task CopyFiles(string from, string to, ProgressBar bar, Label percent) { long total_size = new FileInfo(from).Length; using (var outStream = new FileStream(to, FileMode.Create, FileAccess.Write)) { using (var inStream = new FileStream(from, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[1024 * 1024]; long total_read = 0; while (total_read < total_size) { int read = await inStream.ReadAsync(buffer, 0, buffer.Length); await outStream.WriteAsync(buffer, 0, read); total_read += read; await System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => { long a = total_read * 100 / total_size; bar.Value = a; percent.Content = a + " %"; })); } } } }
public async Task<HttpResponseMessage> UploadFile() { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); if (!Request.Content.IsMimeMultipartContent()) { response.StatusCode = HttpStatusCode.UnsupportedMediaType; } else { UserPrincipal loggedInUser = (UserPrincipal)HttpContext.Current.User; MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider(); await Request.Content.ReadAsMultipartAsync(provider); Task<byte[]> fileData = provider.Contents.First().ReadAsByteArrayAsync(); string fileName = string.Format("{0}.jpg", Guid.NewGuid().ToString()); string directory = string.Format(@"{0}Uploads\{1}", AppDomain.CurrentDomain.BaseDirectory, loggedInUser.AccountSession.ClubId); if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); using (FileStream fs = new FileStream(string.Format(@"{0}\{1}", directory, fileName), FileMode.OpenOrCreate)) { await fs.WriteAsync(fileData.Result, 0, fileData.Result.Length); fs.Close(); } response.Content = new ObjectContent<string>(fileName, new JsonMediaTypeFormatter()); } return response; }
private async void DoImage() { var url = ""; if (ShareData.ImagesUrls.TryTake(out url)) { Console.WriteLine("处理图片URL:" + url); using (HttpClient client = new HttpClient(new MyHttpClienHanlder(DictParas))) { if (!Directory.Exists(SavePath)) { Directory.CreateDirectory(SavePath); } var bytes = await client.GetByteArrayAsync(url); string filename = url.Substring(url.LastIndexOf('/') + 1); if (filename.IndexOf('-') > 0) { filename = filename.Substring(filename.IndexOf('-') + 1); } using (FileStream fs = new System.IO.FileStream(SavePath + "//" + filename, System.IO.FileMode.CreateNew)) { await fs.WriteAsync(bytes, 0, bytes.Length); fs.Close(); } //var fs = new System.IO.FileStream(SavePath + "//" + filename, System.IO.FileMode.CreateNew); //fs.Write(bytes, 0, bytes.Length); //fs.Close(); } } }
public async Task <string> CaptureAndSaveAsync() { if (!(await RequestStoragePermission())) { var missingPermissions = string.Join(", ", nameof(StoragePermission)); throw new Exception($"{missingPermissions} permission(s) are required."); } var bytes = await CaptureAsync(); Java.IO.File picturesFolder = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim); string date = DateTime.Now.ToString().Replace("/", "-").Replace(":", "-"); try { string filePath = System.IO.Path.Combine(picturesFolder.AbsolutePath + "/Camera", "Screnshot-" + date + ".png"); using (System.IO.FileStream SourceStream = System.IO.File.Open(filePath, System.IO.FileMode.OpenOrCreate)) { SourceStream.Seek(0, System.IO.SeekOrigin.End); await SourceStream.WriteAsync(bytes, 0, bytes.Length); } return(filePath); } catch (Exception ex) { return(ex.Message); } }
static async void OpenReadWriteFileAsync(string fileName) { byte[] buffer = null; try { using (Stream streamRead = new FileStream(@fileName, FileMode.Open, FileAccess.Read)) { buffer = new byte[streamRead.Length]; Console.WriteLine("In Read Operation Async"); Task readData = streamRead.ReadAsync(buffer, 0, (int)streamRead.Length); await readData; } using (Stream streamWrite = new FileStream(@"MyFileAsync(bak).txt", FileMode.Create, FileAccess.Write)) { Console.WriteLine("In Write Operation Async "); Task writeData = streamWrite.WriteAsync(buffer, 0, buffer.Length); await writeData; } } catch (Exception) { throw; } }
public static void Main(string[] args) { var urls = Console.In.ReadToEnd().Split(new string[]{Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries); var dir = args[0]; Func<string, Task> download = async (url) => { var wc = new WebClient(); var uri = new Uri(url); var fileName = Path.Combine(dir, Path.GetFileName(url)); try { byte[] buf = await wc.DownloadDataTaskAsync(uri); using (var fs = new FileStream(fileName, FileMode.Create)) { await fs.WriteAsync(buf, 0, buf.Length); } Console.WriteLine("download: {0} => {1}", url, fileName); } catch (Exception ex) { Console.WriteLine("failed: {0}, {1}", url, ex.Message); } }; Task.WaitAll((from url in urls select download(url)).ToArray()); }
public async Task<string> GetSpeakerImagePath (Conference conference, Speaker speaker) { string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); string localFilename = conference.Slug + "-" + speaker.Slug + ".png"; string localPath = Path.Combine (documentsPath, localFilename); byte[] bytes = null; if (!File.Exists (localPath)) { using (var httpClient = new HttpClient (new NativeMessageHandler ())) { try { bytes = await httpClient.GetByteArrayAsync (speaker.ImageUrl); } catch (OperationCanceledException opEx) { Insights.Report (opEx); return null; } catch (Exception e) { Insights.Report (e); return null; } //Save the image using writeAsync FileStream fs = new FileStream (localPath, FileMode.OpenOrCreate); await fs.WriteAsync (bytes, 0, bytes.Length); } } return localPath; }
public async Task SharePoster(string title, string image) { var intent = new Intent(Intent.ActionSend); intent.SetType("image/png"); Guid guid = Guid.NewGuid(); var path = Environment.GetExternalStoragePublicDirectory(Environment.DataDirectory + Java.IO.File.Separator + guid + ".png"); HttpClient client = new HttpClient(); var httpResponse = await client.GetAsync(image); byte[] imageBuffer = await httpResponse.Content.ReadAsByteArrayAsync(); if (File.Exists(path.AbsolutePath)) { File.Delete(path.AbsolutePath); } using (var os = new System.IO.FileStream(path.AbsolutePath, System.IO.FileMode.Create)) { await os.WriteAsync(imageBuffer, 0, imageBuffer.Length); } intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.FromFile(path)); var intentChooser = Intent.CreateChooser(intent, "Share via"); Activity activity = Forms.Context as Activity; activity.StartActivityForResult(intentChooser, 100); }
public async Task <string> CaptureAndSaveAsync() { try { var bytes = await CaptureAsync(); Java.IO.File picturesFolder = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures); string date = DateTime.Now.ToString().Replace("/", "-").Replace(":", "-"); var directory = $"{picturesFolder.AbsolutePath}/Screenshots"; if (!System.IO.Directory.Exists(directory)) { System.IO.Directory.CreateDirectory(directory); } string filePath = System.IO.Path.Combine(directory, "Screnshot-" + date + ".png"); using (System.IO.FileStream SourceStream = System.IO.File.Open(filePath, System.IO.FileMode.OpenOrCreate)) { SourceStream.Seek(0, System.IO.SeekOrigin.End); await SourceStream.WriteAsync(bytes, 0, bytes.Length); } return(filePath); } catch (Exception ex) { return(ex.Message); } }
/// <summary> /// Save an Image and resize if necessary /// </summary> /// <param name="uploadImage"></param> /// <returns></returns> public async Task<UploadImage> SaveAndResizeImage(UploadImage uploadImage) { try { var uploadPath = Path.Combine(this.filePath, Path.GetFileName(uploadImage.fileName)); using (var fs = new FileStream(uploadPath, FileMode.Create)) { await fs.WriteAsync(uploadImage.file, 0, uploadImage.file.Length); var resizeImage = imageHelper.GetImage(uploadImage.file); if (imageHelper.ResizeNeeded(resizeImage, maxWidth, maxHeight)) { var resized = imageHelper.ResizeImage(resizeImage, maxWidth, maxHeight); using (var resizedFs = new FileStream(Path.Combine(this.filePath, Path.GetFileName(GetResizedFileName(uploadImage.fileName))), FileMode.Create)) { await resizedFs.WriteAsync(resized, 0, resized.Length); // Set the original image byte stream to the new resized value uploadImage.file = resized; } } } } catch (Exception exception) { throw new Exception("Error saving file: " + exception.Message); } return uploadImage; }
async Task ReadAudioAsync () { using (var fileStream = new FileStream (filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { while (true) { if (endRecording) { endRecording = false; break; } try { // Keep reading the buffer while there is audio input. int numBytes = await audioRecord.ReadAsync (audioBuffer, 0, audioBuffer.Length); await fileStream.WriteAsync (audioBuffer, 0, numBytes); // Do something with the audio input. } catch (Exception ex) { Console.Out.WriteLine (ex.Message); break; } } fileStream.Close (); } audioRecord.Stop (); audioRecord.Release (); isRecording = false; RaiseRecordingStateChangedEvent (); }
public async Task Save([NotNull] string fileName, [NotNull] byte[] content) { using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate)) { await fs.WriteAsync(content, 0, content.Length); } }
public async Task UnpackAsync(Stream input, DirectoryInfo folder, bool append) { if (input == null) throw new ArgumentNullException("input"); if (folder == null) throw new ArgumentNullException("folder"); var mode = FileMode.Create; if (append) { mode = FileMode.Append; } foreach (var fileHeader in NetworkHelper.ReadString(input, _buffer).Split(PackageHelper.FileSeparator)) { var name = fileHeader.Substring(0, fileHeader.IndexOf(PackageHelper.SizeSeparator)); var filePath = Path.Combine(folder.FullName, name); var folderPath = Path.GetDirectoryName(filePath); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } using (var output = new FileStream(filePath, mode)) { int readBytes; while ((readBytes = await input.ReadAsync(_buffer, 0, _buffer.Length)) != 0) { await output.WriteAsync(_buffer, 0, readBytes); } } } }
public async Task<PendingChallenge> AcceptChallengeAsync(string domain, string siteName, AuthorizationResponse authorization) { var challenge = authorization?.Challenges.FirstOrDefault(c => c.Type == "http-01"); if (challenge == null) { Error("the server does not accept challenge type http-01"); return null; } Info($"accepting challenge {challenge.Type}"); var keyAuthorization = client.GetKeyAuthorization(challenge.Token); var acmeChallengePath = System.IO.Directory.GetCurrentDirectory(); var challengeFile = Path.Combine(acmeChallengePath, challenge.Token); using (var fs = new FileStream(challengeFile, FileMode.Create, FileAccess.Write, FileShare.None)) { var data = Encoding.ASCII.GetBytes(keyAuthorization); await fs.WriteAsync(data, 0, data.Length); } return new PendingChallenge() { Instructions = $"Copy {challengeFile} to https://{domain ?? siteName}/.well-known/acme-challenge/{challenge.Token}", Complete = () => client.CompleteChallengeAsync(challenge) }; }
public async Task<bool> Process(ICrawler crawler, PropertyBag propertyBag) { if (propertyBag.StatusCode != HttpStatusCode.OK || propertyBag.Response == null) { return true; } string extension = MapContentTypeToExtension(propertyBag.ContentType); if (extension.IsNullOrEmpty()) { return true; } propertyBag.Title = propertyBag.Step.Uri.PathAndQuery; using (TempFile temp = new TempFile()) { temp.FileName += "." + extension; using (FileStream fs = new FileStream(temp.FileName, FileMode.Create, FileAccess.Write, FileShare.Read, 0x1000)) { await fs.WriteAsync(propertyBag.Response, 0, propertyBag.Response.Length); } ParserContext context = new ParserContext(temp.FileName); ITextParser parser = ParserFactory.CreateText(context); propertyBag.Text = parser.Parse(); } return true; }
public async Task <IHttpActionResult> UploadPhoto() { if (!Request.Content.IsMimeMultipartContent()) { return(BadRequest()); } var provider = new MultipartMemoryStreamProvider(); string root = System.Web.HttpContext.Current.Server.MapPath("~/webroot/"); await Request.Content.ReadAsMultipartAsync(provider); foreach (var file in provider.Contents) { var filename = file.Headers.ContentDisposition.FileName.Trim('\"'); var identity = ((ClaimsIdentity)User.Identity).FindFirst(ClaimTypes.SerialNumber); var extension = filename.Substring(filename.IndexOf('.')); //var extension = filename.Substring(filename.Length - 4); var finalName = identity.Value + extension; byte[] fileArray = await file.ReadAsByteArrayAsync(); using (System.IO.FileStream fs = new System.IO.FileStream(root + finalName, System.IO.FileMode.Create)) { await fs.WriteAsync(fileArray, 0, fileArray.Length); } var user = await _database.GetUser(identity.Value); //var physicalFileSystem = new PhysicalFileSystem(Path.Combine(root, "webroot")); /*user.Photo = "https://datingapi20180316115426.azurewebsites.net/webroot/" + finalName;*/ user.Photo = "http://localhost:56761/webroot/" + finalName; await _database.Update(user); } return(Ok("File uploaded")); }
public async Task Perform() { using (var sourceStream = new FileStream(_path, FileMode.Create, FileAccess.Write, FileShare.None, DefaultBufferSize, FileOptions.Asynchronous)) { await sourceStream.WriteAsync(_fileMessage.FileContent, 0, _fileMessage.FileContent.Length); } }
private static void WriteToDisc() { while (true) { var file = _queue.Take(); try { using (var sourceStream = new FileStream( file.Path, FileMode.Append, FileAccess.Write, FileShare.Write, bufferSize: 4096, useAsync: true)) { Task theTask = sourceStream.WriteAsync(file.Content, 0, file.Content.Length); ConsoleWriter.WriteLine("Saving to disk: " + file.Path); } } catch (IOException iex) { ConsoleWriter.WriteLine(iex.Message); } catch (Exception ex) { ConsoleWriter.WriteLine(ex.Message); } } }
static async Task WrAsynch(string filePath, string txt) { byte[] text = Encoding.Unicode.GetBytes(txt); using (FileStream stream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true)) { await stream.WriteAsync(text, 0, text.Length); } }
/// <summary> /// Writes all test async /// </summary> /// <param name="filePath"></param> /// <param name="text"></param> /// <returns></returns> public static async Task WriteAllTextAsync(string filePath, string text) { byte[] encodedText = Encoding.UTF8.GetBytes(text); using (var sourceStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true)) { await sourceStream.WriteAsync(encodedText, 0, encodedText.Length).ConfigureAwait(false); } }
public async Task <IHttpActionResult> UploadFile() { var path = "/Content/images/upload/test/"; if (!Request.Content.IsMimeMultipartContent()) { return(BadRequest()); } var provider = new MultipartMemoryStreamProvider(); // путь к папке на сервере string root = System.Web.HttpContext.Current.Server.MapPath("~" + path); await Request.Content.ReadAsMultipartAsync(provider); foreach (var file in provider.Contents) { var filename = file.Headers.ContentDisposition.FileName.Trim('\"'); byte[] fileArray = await file.ReadAsByteArrayAsync(); using (System.IO.FileStream fs = new System.IO.FileStream(root + filename, System.IO.FileMode.Create)) { await fs.WriteAsync(fileArray, 0, fileArray.Length); } } return(Ok("файлы загружены")); }
public static async Task WriteAllTextAsync(string path, string contents) { using (var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: BufferSize, useAsync: true)) { var encoded = Encoding.Default.GetBytes(contents); await stream.WriteAsync(encoded, 0, encoded.Length); } }
public void NullBufferThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { Assert.Throws<ArgumentNullException>("buffer", () => FSAssert.CompletesSynchronously(fs.WriteAsync(null, 0, 1))); } }
public async void DownloadHistory ( ImageView imageView,string url,ProgressBar Pbar =null) { if (string.IsNullOrEmpty(url)) return; try { int index = url.LastIndexOf ("/"); string localFilename = url.Substring (index + 1); var webClient = new WebClient (); var uri = new Uri (url); webClient.DownloadProgressChanged += (sender, e) => {if(Pbar!=null) Pbar.Progress=e.ProgressPercentage; }; documentsPath = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal); localPath = System.IO.Path.Combine (documentsPath, localFilename); var localImage = new Java.IO.File (localPath); if (localImage.Exists ()) { var imgUri=Android.Net.Uri.Parse("file:"+localPath); imageView.SetImageURI(imgUri); } else { byte[] bytes = null; bytes = await webClient.DownloadDataTaskAsync (uri); FileStream fs = new FileStream (localPath, FileMode.Create); await fs.WriteAsync (bytes, 0, bytes.Length); fs.Close (); var imgUri=Android.Net.Uri.Parse("file:"+localPath); imageView.SetImageURI(imgUri); // teamBitmap = await BitmapFactory.DecodeByteArrayAsync (bytes, 0, bytes.Length); // imageView.SetImageBitmap (teamBitmap); } } catch (TaskCanceledException) { return; } catch (Exception) { return; } }
async void downloadAsync(object sender, System.EventArgs ea) { webClient = new WebClient (); //An large image url var url = new Uri ("http://photojournal.jpl.nasa.gov/jpeg/PIA15416.jpg"); byte[] bytes = null; webClient.DownloadProgressChanged += HandleDownloadProgressChanged; this.downloadButton.SetTitle ("Cancel",UIControlState.Normal); this.downloadButton.TouchUpInside -= downloadAsync; this.downloadButton.TouchUpInside += cancelDownload; infoLabel.Text = "Downloading..."; //Start download data using DownloadDataTaskAsync try{ bytes = await webClient.DownloadDataTaskAsync(url); } catch(TaskCanceledException){ Console.WriteLine ("Task Canceled!"); return; } catch(Exception e) { Console.WriteLine (e.ToString()); return; } string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); string localFilename = "downloaded.png"; string localPath = Path.Combine (documentsPath, localFilename); infoLabel.Text = "Download Complete"; //Save the image using writeAsync FileStream fs = new FileStream (localPath, FileMode.OpenOrCreate); await fs.WriteAsync (bytes, 0, bytes.Length); Console.WriteLine("localPath:"+localPath); //Resizing image is time costing, using async to avoid blocking the UI thread UIImage image = null; SizeF imageViewSize = imageView.Frame.Size; infoLabel.Text = "Resizing Image..."; await Task.Run( () => { image = UIImage.FromFile(localPath).Scale(imageViewSize); } ); Console.WriteLine ("Loaded!"); imageView.Image = image; infoLabel.Text = "Click Dowload button to download the image"; this.downloadButton.TouchUpInside -= cancelDownload; this.downloadButton.TouchUpInside += downloadAsync; this.downloadButton.SetTitle ("Download", UIControlState.Normal); this.downloadProgress.Progress = 0.0f; }
public async Task WriteFileAsync(string fileName, byte[] fileBytes) { EnsureDirectoryExists(fileName); using (var fs = new FileStream(fileName, FileMode.Create, System.IO.FileAccess.Write, FileShare.Read)) { await fs.WriteAsync(fileBytes, 0, fileBytes.Length); } }
public async Task CreateAndWriteAsyncToFile (byte[] data, string aFileName) { using (FileStream stream = new FileStream (aFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read, 1024 * 4, true)) { await stream.WriteAsync (data, 0, data.Length); } }
public static async Task WriteFileWithContent(string filePath, string content) { var encodedText = Encoding.UTF8.GetBytes(content ?? ""); using (var sourceStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true)) { await sourceStream.WriteAsync(encodedText, 0, encodedText.Length); }; }
public async Task SaveFileAsync(ResourceForSavingModel model) { CreateDirectoryIfDoNotExists(model); string fileFullPath = model.FilePath; using (FileStream fsStream = new FileStream(fileFullPath, FileMode.Create)) { await fsStream.WriteAsync(model.ResourceContent, 0, model.ResourceContent.Length); } }
public async Task CreateAndWriteAsyncToFile() { using (FileStream stream = new FileStream("test.dat", FileMode.Create, FileAccess.Write, FileShare.None, 4096, true)) { byte[] data = new byte[100000]; new Random().NextBytes(data); await stream.WriteAsync(data, 0, data.Length); } }
public async Task<HttpResponseMessage> Save(Stream dataStream, User user, string photoDescription, double? rating, string fileExtension, bool isAvatar) { var bufferOriginal = new byte[dataStream.Length]; var maxSize = user.Account.MaxSize; var photos = user.Photos; var currentSize = (photos == null ? 0 : photos.Sum(p => p.Size)); // counting in MB if (maxSize != null && currentSize + (double) bufferOriginal.Length / 1024 / 1024 > maxSize) { var response = new HttpResponseMessage(HttpStatusCode.MethodNotAllowed); response.Content = new StringContent("The file doesn't meet size limit requirements", Encoding.UTF8, "text/plain"); return response; }; await dataStream.ReadAsync(bufferOriginal, 0, (int)dataStream.Length); //var prefix = System.Configuration. .ConfigurationManager.AppSettings["pathSave"] ?? "~/images/"; var prefix = "~/images/"; var uploadFolderOriginal = prefix + user.Login + "/original/"; var uploadFolderPreview = prefix + user.Login + "/preview/"; var rootOriginal = HttpContext.Current.Server.MapPath(uploadFolderOriginal); var rootPreview = HttpContext.Current.Server.MapPath(uploadFolderPreview); Directory.CreateDirectory(rootOriginal); Directory.CreateDirectory(rootPreview); var bufferPreview = PhotoConverter.Resize(bufferOriginal, 100, 100); var suffix = Guid.NewGuid() + "." + fileExtension; rootOriginal += suffix; uploadFolderOriginal += suffix; rootPreview += suffix; uploadFolderPreview += suffix; using (var stream = new FileStream(rootOriginal, FileMode.OpenOrCreate)) { await stream.WriteAsync(bufferOriginal, 0, bufferOriginal.Length); } using (var stream = new FileStream(rootPreview, FileMode.OpenOrCreate)) { await stream.WriteAsync(bufferPreview, 0, bufferPreview.Length); } var photo = new Photo { Description = photoDescription, User = user, Size = (double)dataStream.Length / 1024 / 1024, Rating = rating, SrcOriginal = uploadFolderOriginal, SrcPreview = uploadFolderPreview, }; photosDb.Add(photo); photosDb.Save(); var result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StringContent("Successful upload", Encoding.UTF8, "text/plain"); return result; }
private async Task WriteTextAsync(string filePath, string text) { byte[] encodedText = Encoding.Unicode.GetBytes(text); using (FileStream sourceStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None, bufferSize: 4096,useAsync: true)) { await sourceStream.WriteAsync(encodedText, 0, encodedText.Length); }; }
public async Task SaveROMAsync(byte[] romData, bool backupOriginal) { if(backupOriginal == true) await BackupROM(); // Now save ROM data to original file using (FileStream fs = new FileStream(romPath, FileMode.Truncate, FileAccess.Write, FileShare.None, 4096, true)) { await fs.WriteAsync(romData, 0, romData.Length); } }
private static void WriteFilesToLocal(IEnumerable<HttpContent> files) { foreach (var file in files) { string fileName = file.Headers.ContentDisposition.FileName; byte[] fileData = file.ReadAsByteArrayAsync().Result; using (var fileStream = new FileStream("/Users/Public/" + fileName, FileMode.Create)) fileStream.WriteAsync(fileData, 0, fileData.Length); } }
public async Task<Bitmap> downloadAsync (string uri) { if (uri == null) return null; int index = uri.LastIndexOf ("/"); string localFilename = uri.Substring (index + 1); webClient = new WebClient (); var url = new Uri (uri); byte[] bytes = null; try { bytes = await webClient.DownloadDataTaskAsync (url); } catch (TaskCanceledException Ex) { Log.Error ("downloadAsync:", Ex.Message); return null; } catch (Exception Ex) { Log.Error ("downloadAsync:", Ex.Message); return null; } string documentsPath = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal); string localPath = System.IO.Path.Combine (documentsPath, localFilename); //Sive the Image using writeAsync FileStream fs = new FileStream (localPath, FileMode.OpenOrCreate); await fs.WriteAsync (bytes, 0, bytes.Length); //Console.WriteLine("localPath:"+localPath); fs.Close (); BitmapFactory.Options options = new BitmapFactory.Options (); options.InJustDecodeBounds = true; await BitmapFactory.DecodeFileAsync (localPath, options); // options.InSampleSize = options.OutWidth > options.OutHeight ? options.OutHeight / imageview.Height : options.OutWidth / imageview.Width; options.InJustDecodeBounds = false; Bitmap bitmap = await BitmapFactory.DecodeFileAsync (localPath, options); return (bitmap); }
// .NET > 4.5 async static void AsyncDemo() { using (Stream s = new System.IO.FileStream("test.txt", FileMode.Create)) { byte[] block = { 1, 2, 3, 4, 5 }; await s.WriteAsync(block, 0, block.Length); // Выполнить запись асинхронно s.Position = 0; // Переместиться обратно в начало // Читать из потока в массив block: Console.WriteLine(await s.ReadAsync(block, 0, block.Length)); // 5 } }
public async Task CaptureAndSaveAsync() { var bytes = await CaptureAsync(); Java.IO.File picturesFolder = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures); string date = DateTime.Now.ToString().Replace("/", "-").Replace(":", "-"); string filePath = System.IO.Path.Combine(picturesFolder.AbsolutePath, "Screnshot-" + date + ".png"); using (System.IO.FileStream SourceStream = System.IO.File.Open(filePath, System.IO.FileMode.OpenOrCreate)) { SourceStream.Seek(0, System.IO.SeekOrigin.End); await SourceStream.WriteAsync(bytes, 0, bytes.Length); } }
public async void UploadNewsPic(IEnumerable <FileAsClass> files, string tempPicPath) { foreach (var file in files) { using (System.IO.FileStream _FileStream = new System.IO.FileStream(tempPicPath + file.FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { await _FileStream.WriteAsync(file.FileBuffer, 0, file.FileBuffer.Length); _FileStream.Close(); } } }
public async Task SaveFileTo(string path) { string filename = IO.Path.GetFileName(this.Path); string outPath = IO.Path.Combine(path, "RomFS"); byte[] data = this.SafeGetBuffer(); if (!IO.Directory.Exists(outPath)) { IO.Directory.CreateDirectory(outPath); } using (var fs = new IO.FileStream(IO.Path.Combine(outPath, filename), IO.FileMode.Create, IO.FileAccess.Write, IO.FileShare.None)) await fs.WriteAsync(data, 0, data.Length); }
protected async Task CreateCache(byte[] data, string filepath) { try { using (var fs = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, FileAccess.Write)) { await fs.WriteAsync(data, 0, data.Length); } } catch (System.IO.IOException e) { Debug.WriteLine("Message={0},StackTrace={1}", e.Message, e.StackTrace); await Task.Delay(100); await CreateCache(data, filepath); } }
/// <summary> /// Downloads a file to local machine /// </summary> /// <param name="path"></param> /// <param name="fileName"></param> /// <param name="data"></param> /// <returns></returns> protected async Task Download(string path, string fileName, byte[] data) { if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentNullException(nameof(path)); } path = I.Path.GetDirectoryName(path); if (!I.Directory.Exists(path)) { I.Directory.CreateDirectory(path); } path = I.Path.Combine(path, fileName); using (I.FileStream fileStream = I.File.Create(path)) { await fileStream.WriteAsync(data, 0, data.Length); } }
private async Task <string> SaveImage(HttpFile photo) { string root = System.Web.HttpContext.Current.Server.MapPath("~"); if (!System.IO.Directory.Exists(root)) { System.IO.Directory.CreateDirectory(root); } byte[] fileArray = photo.Buffer; var filename = photo.FileName; string guid = Guid.NewGuid().ToString(); string path = $"/Files/{guid + Path.GetExtension(filename)}"; using (System.IO.FileStream fs = new System.IO.FileStream(root + path , System.IO.FileMode.Create)) { await fs.WriteAsync(fileArray, 0, fileArray.Length); } return(path); }
static public int WriteAsync(IntPtr l) { try { System.IO.FileStream self = (System.IO.FileStream)checkSelf(l); System.Byte[] a1; checkArray(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); System.Threading.CancellationToken a4; checkValueType(l, 5, out a4); var ret = self.WriteAsync(a1, a2, a3, a4); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
private async void saveAsToolStripMenuItem_Click(object sender, EventArgs e) { // Displays a SaveFileDialog so the user can save the Image // assigned to Button2. SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Color Files (*.col)|*.col"; saveFileDialog1.Title = "Save a color File"; saveFileDialog1.ShowDialog(); // If the file name is not an empty string open it for saving. if (saveFileDialog1.FileName != "") { using (System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile()) { string s = currentCharacter.ToColFormat(); var b = Encoding.ASCII.GetBytes(s); // todo can we replace the palettehelper method with this? fs.Seek(0, SeekOrigin.End); await fs.WriteAsync(b, 0, b.Length); } } }
public static async Task <bool> SaveFile <T>(string path, T value) { try { await fileStreamSemaphore.WaitAsync(); var encodedContent = Serialize(value); if (encodedContent == null || encodedContent.Length == 0) { return(false); } using (var fileStream = new System.IO.FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true)) { await fileStream.WriteAsync(encodedContent, 0, encodedContent.Length); }; return(System.IO.File.Exists(path)); } catch (Exception) { throw; } finally { fileStreamSemaphore.Release(); } }
public async Task <IHttpActionResult> PostFile() { if (!Request.Content.IsMimeMultipartContent()) { return(BadRequest()); } var provider = new MultipartMemoryStreamProvider(); // путь к папке на сервере string path = ConfigurationManager.AppSettings["pathUploadFiles"]; string root = System.Web.HttpContext.Current.Server.MapPath(path); root += "Temp/"; DirectoryInfo di = Directory.CreateDirectory(root); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } await Request.Content.ReadAsMultipartAsync(provider); foreach (var _file in provider.Contents) { var filename = _file.Headers.ContentDisposition.FileName.Trim('\"'); byte[] fileArray = await _file.ReadAsByteArrayAsync(); using (System.IO.FileStream fs = new System.IO.FileStream(root + filename, System.IO.FileMode.Create)) { await fs.WriteAsync(fileArray, 0, fileArray.Length); } } return(Ok("Файлы загружены в " + root)); }
public async Task<IHttpActionResult> PutDirWarehouse(HttpRequestMessage request) //HttpPostedFileBase upload { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10)); //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //dbRead = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) /* int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocAccounts")); if (iRight == 3) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0))); */ if(field.DirEmployeeID != 1) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0))); //Разные Функции function.NumberDecimalSeparator(); //Получам настройки sysSetting = await db.SysSettings.FindAsync(1); //Получаем сотрудника: если к нему привязан Склад и/или Организация, то выбираем документы только по этим характеристикам Models.Sklad.Dir.DirEmployee dirEmployee = await db.DirEmployees.FindAsync(field.DirEmployeeID); #endregion #region Параметры //paramList -список параметров var paramList = request.GetQueryNameValuePairs(); //Параметры sheetName = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "sheetName", true) == 0).Value; DirContractorIDOrg = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirContractorIDOrg", true) == 0).Value); DirContractorID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirContractorID", true) == 0).Value); DirWarehouseID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirWarehouseID", true) == 0).Value); #endregion #region Сохранение OleDbConnection OleDbConn = null; try { //Алгоритм: //0. Проверка //1. Генерируем ID-шник "SysGens" //2. Получаем файл и сохраняем в папаке "Uploads" с именем: authCookie["CookieB"] + "_" + sysGen.SysGenID //3. Считываем Эксель файл // [Код товара], [Категория], [Товар] //Получаем категорию "APPLE/ iPhone 4S/ Распродажа/ Распродажа Swarovski /" //Разделитель "/" и убираем первый пробел //Проверяем каждую получиную категорию: есть ли связка (Sub, Name) //Если нет - вносим категорию, а потом товар: ([Код товара], [Товар]) //Если есть - вносим товар: ([Код товара], [Товар]) // *** Важно *** *** *** //1.Находим максимальный код группы //2.Создаём коды групп (Макс + 1) //3.Создаём коды товаров(из Эксель) #region 0. Проверка *** *** *** *** *** *** *** if (!Request.Content.IsMimeMultipartContent()) Ok(returnServer.Return(false, "{" + "'msgType':'1', 'msg':'" + Classes.Language.Sklad.Language.msg57(0) + "'}")); #endregion #region 1. Генерируем ID-шник "SysGens" *** *** *** *** *** *** *** Models.Sklad.Sys.SysGen sysGen = new Models.Sklad.Sys.SysGen(); sysGen.SysGenDisc = ""; sysGen.SysGenID = null; //if (!ModelState.IsValid) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg91)); //return BadRequest(ModelState); db.Entry(sysGen).State = EntityState.Added; await db.SaveChangesAsync(); #endregion #region 2. Получаем файл и сохраняем в папаке "Uploads" с именем: authCookie["CookieB"] + "_" + sysGen.SysGenID *** *** *** *** *** *** *** string filePatch = ""; var provider = new MultipartMemoryStreamProvider(); string root = System.Web.HttpContext.Current.Server.MapPath("~/UsersTemp/FileStock/"); await Request.Content.ReadAsMultipartAsync(provider); foreach (var file in provider.Contents) { if (file.Headers.ContentDisposition.FileName != null) { var filename = file.Headers.ContentDisposition.FileName.Trim('\"'); var ext = Path.GetExtension(filename); filePatch = root + field.DirCustomersID + "_" + sysGen.SysGenID + ext; byte[] fileArray = await file.ReadAsByteArrayAsync(); using (System.IO.FileStream fs = new System.IO.FileStream(filePatch, System.IO.FileMode.Create)) //root + filename { await fs.WriteAsync(fileArray, 0, fileArray.Length); } } } #endregion #region 3. Получаем максимальный код группы var queryMaxGroupID = await Task.Run(() => ( from x in db.DirNomens where x.DirNomenCategoryID == null select x ).MaxAsync(x => x.DirNomenID)); iMaxGroupID = queryMaxGroupID + 1; if (iMaxGroupID == null || iMaxGroupID == 0) iMaxGroupID = 1; #endregion #region 4. Считываем Эксель файл if (filePatch.Length > 0) { //1. Получаем категорию "APPLE/ iPhone 4S/ Распродажа/ Распродажа Swarovski /" //2. Разделитель "/" и убираем первый пробел //3. Проверяем каждую получиную категорию: есть ли связка (Sub, Name) //4. Если нет - вносим категорию, а потом товар: ([Код товара], [Товар]) //5. Если есть - вносим товар: ([Код товара], [Товар]) string sExcelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePatch + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1;\""; //8.0 using (OleDbConn = new OleDbConnection(sExcelConnectionString)) { OleDbConn.Open(); using (OleDbCommand OleDbCmd = new OleDbCommand("", OleDbConn)) { #region 1. Таблица "Товар" OleDbCmd.CommandText = "SELECT * FROM [" + sheetName + "$]"; OleDbCmd.Parameters.Clear(); using (OleDbDataReader dr = OleDbCmd.ExecuteReader()) { using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { while (dr.Read()) { if (dr["Код товара"].ToString().Length == 5) { //Read string DirNomenID = dr["Код товара"].ToString(); string GroupList = dr["Категория"].ToString(); string DirNomenName = dr["Товар"].ToString(); //Create Group in database await Task.Run(() => GroupCreate(Convert.ToInt32(DirNomenID), GroupList, DirNomenName)); } else { alCodeNot.Add(dr["Код товара"].ToString() + " - " + dr["Категория"].ToString() + " - " + dr["Товар"].ToString()); //... } } ts.Commit(); } } #endregion #region 2. Таблицы: Характеристики, Приходная накладная (Шапка + Спецификация), Остатки, Партии. (Новый алгоритм алгоритм: одна приходная накладная) //1. Надо получить все точки из Эксель (GROUP BY) //2. И делать SELECT по точкам, что бы сформировать приходные накладные по точкам OleDbCmd.CommandText = "SELECT [Точка] FROM [" + sheetName + "$] GROUP BY [Точка] ORDER BY [Точка]"; OleDbCmd.Parameters.Clear(); ArrayList alDirWarehouseID = new ArrayList(); using (OleDbDataReader dr = OleDbCmd.ExecuteReader()) { while (dr.Read()) { alDirWarehouseID.Add(dr["Точка"].ToString()); } } //Формируем "Приходные накладные" using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { for (int i = 0; i < alDirWarehouseID.Count; i++) { Models.Sklad.Doc.DocPurch docPurch = new Models.Sklad.Doc.DocPurch(); ArrayList alWrite = new ArrayList(); //OleDbCmd.CommandText = "SELECT * FROM [" + sheetName + "$] WHERE Дата=@pDate"; OleDbCmd.CommandText = "SELECT * FROM [" + sheetName + "$] WHERE Точка=@Точка"; // ORDER BY [Код товара], [Дата] DESC OleDbCmd.Parameters.Clear(); OleDbCmd.Parameters.AddWithValue("@Точка", alDirWarehouseID[i].ToString()); using (OleDbDataReader dr = OleDbCmd.ExecuteReader()) { while (dr.Read()) { if (dr["Код товара"].ToString().Length == 5) { Field1 field1 = new Field1(); field1.DirNomenID = Convert.ToInt32(dr["Код товара"].ToString()); field1.DocDate = dr["Дата"].ToString(); //field1.DirWarehouseID = ReturnDirWarehouseID(dr["Точка"].ToString()); field1.DirWarehouseID = await Task.Run(() => ReturnDirWarehouseID(dr["Точка"].ToString())); field1.Quantity = Convert.ToInt32(dr["Остаток"].ToString()); field1.PriceVAT = Convert.ToDouble(dr["Закуп цена за ед"].ToString()); field1.PriceCurrency = Convert.ToDouble(dr["Закуп цена за ед"].ToString()); field1.PriceRetailVAT = Convert.ToDouble(dr["Цена-1"].ToString()); field1.PriceRetailCurrency = Convert.ToDouble(dr["Цена-1"].ToString()); field1.PriceWholesaleVAT = Convert.ToDouble(dr["Цена-2"].ToString()); field1.PriceWholesaleCurrency = Convert.ToDouble(dr["Цена-2"].ToString()); field1.PriceIMVAT = Convert.ToDouble(dr["Цена-3"].ToString()); field1.PriceIMCurrency = Convert.ToDouble(dr["Цена-3"].ToString()); field1.DirCharColourID = ReturnDirCharColourID(dr["Поставщик"].ToString()); field1.DirCharTextureID = ReturnDirCharTextureID(dr["Примечание"].ToString()); alWrite.Add(field1); } else { //alCodeNot.Add(dr["Код товара"].ToString() + " - " + dr["Категория"].ToString() + " - " + dr["Товар"].ToString()); //... } } } //Create Purchase documents and Remnants of goods in stock docPurch = await Task.Run(() => DocsCreate(alWrite)); #region Чистим пустые партии товара, но только соотвутствующие Номеру документа, что бы НЕ удалить все пустые (0, 0) SQLiteParameter parDocID = new SQLiteParameter("@DocID", System.Data.DbType.Int32) { Value = docPurch.DocID }; await db.Database.ExecuteSqlCommandAsync("DELETE FROM RemParties WHERE DocID=@DocID and Remnant=0; ", parDocID); #endregion } ts.Commit(); } #endregion } OleDbConn.Close(); } } #endregion #region 5. Send dynamic collectionWrapper = new { Msg = "Файл загружен!" }; return Ok(returnServer.Return(true, collectionWrapper)); #endregion } catch (Exception ex) { try { OleDbConn.Close(); OleDbConn.Dispose(); } catch { } return Ok(returnServer.Return(false, exceptionEntry.Return(ex) + i777.ToString())); } #endregion }
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return(tempStream.WriteAsync(buffer, offset, count, cancellationToken)); }
protected override async Task Load(bool forceCacheInvalidation) { //Make sure we have this information. If not, go get it if (_commitFileModel == null) { var data = await Task.Run(() => this.GetApplication().Client.Users[Username].Repositories[Repository].Changesets[Branch].GetDiffs(forceCacheInvalidation)); _commitFileModel = data.First(x => string.Equals(x.File, Filename)); } if (_commitFileModel.Type == "added" || _commitFileModel.Type == "modified") { var filepath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetFileName(Filename)); var content = await Task.Run(() => this.GetApplication().Client.Users[Username].Repositories[Repository].Branches[Branch].Source.GetFile(Filename)); var isText = content.Encoding == null; using (var stream = new System.IO.FileStream(filepath, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { if (isText) { using (var s = new StreamWriter(stream)) await s.WriteAsync(content.Data); } else { var data = Convert.FromBase64String(content.Data); await stream.WriteAsync(data, 0, data.Length); } } if (!isText) { FilePath = filepath; return; } File1 = filepath; } if (_commitFileModel.Type == "removed" || _commitFileModel.Type == "modified") { var changeset = await Task.Run(() => this.GetApplication().Client.Users[Username].Repositories[Repository].Changesets[Branch].GetCommit()); if (changeset.Parents == null || changeset.Parents.Count == 0) { throw new Exception("Diff has no parent. Unable to generate view."); } var parent = changeset.Parents[0].Hash; var filepath2 = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetFileName(Filename) + ".parent"); var content = await Task.Run(() => this.GetApplication().Client.Users[Username].Repositories[Repository].Branches[parent].Source.GetFile(Filename)); var isText = content.Encoding == null; using (var stream = new System.IO.FileStream(filepath2, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { if (isText) { using (var s = new StreamWriter(stream)) await s.WriteAsync(content.Data); } else { var data = Convert.FromBase64String(content.Data); await stream.WriteAsync(data, 0, data.Length); } } if (!isText) { FilePath = filepath2; return; } File2 = filepath2; } if (File1 != null) { FilePath = File1; } else if (File2 != null) { FilePath = File2; } Comments.SimpleCollectionLoad(() => this.GetApplication().Client.Users[Username].Repositories[Repository].Changesets[Branch].Comments.GetComments(forceCacheInvalidation)).FireAndForget(); }
internal async Task LockAsync() { if (Locked) { throw new InternalError($"{nameof(LockAsync)} called while already holding a lock on {Key}"); } for ( ; !Locked;) { if (YetaWFManager.IsSync()) { if (localLock.Wait(10)) { LocalLocked = true; } } else { await localLock.WaitAsync(); LocalLocked = true; } if (LocalLocked) { try { FileStream = new System.IO.FileStream(LockFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None); if (YetaWFManager.IsSync()) { FileStream.Write(new byte[] { 99 }, 0, 1); } else { await FileStream.WriteAsync(new byte[] { 99 }, 0, 1); } Locked = true; } catch (Exception) { } finally { if (!Locked) { if (FileStream != null) { FileStream.Close(); FileStream = null; } } } localLock.Release(); LocalLocked = false; if (Locked) { break; } } if (YetaWFManager.IsSync()) { Thread.Sleep(new TimeSpan(0, 0, 0, 0, 25));// wait a while - this is bad, only works because "other" instance has lock } else { await Task.Delay(new TimeSpan(0, 0, 0, 0, 25));// wait a while } } }