本文整理汇总了C#中System.IO.FileStream.WriteAsync方法的典型用法代码示例。如果您正苦于以下问题:C# FileStream.WriteAsync方法的具体用法?C# FileStream.WriteAsync怎么用?C# FileStream.WriteAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.FileStream
的用法示例。
在下文中一共展示了FileStream.WriteAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: NegativeOffsetThrows
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)));
}
}
示例2: ReadAudioAsync
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 ();
}
示例3: AcceptChallengeAsync
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)
};
}
示例4: Process
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;
}
示例5: CopyFiles
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 + " %";
}));
}
}
}
}
示例6: Save
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);
}
}
示例7: Main
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());
}
示例8: Perform
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);
}
}
示例9: SaveAndResizeImage
/// <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;
}
示例10: UnpackAsync
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);
}
}
}
}
示例11: OpenReadWriteFileAsync
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;
}
}
示例12: UploadFile
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;
}
示例13: WriteToDisc
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);
}
}
}
示例14: GetSpeakerImagePath
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;
}
示例15: WrAsynch
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);
}
}