本文整理汇总了C#中System.IO.FileStream.ReadAsync方法的典型用法代码示例。如果您正苦于以下问题:C# FileStream.ReadAsync方法的具体用法?C# FileStream.ReadAsync怎么用?C# FileStream.ReadAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.FileStream
的用法示例。
在下文中一共展示了FileStream.ReadAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: NegativeOffsetThrows
public void NegativeOffsetThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
Assert.Throws<ArgumentOutOfRangeException>("offset", () =>
FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], -1, 1)));
// buffer is checked first
Assert.Throws<ArgumentNullException>("buffer", () =>
FSAssert.CompletesSynchronously(fs.ReadAsync(null, -1, 1)));
}
}
示例2: getRefByName
private async Task<Errorable<Ref>> getRefByName(RefName refName)
{
FileInfo fiTracker = system.getRefPathByRefName(refName);
if (!fiTracker.Exists) return new RefNameDoesNotExistError(refName);
byte[] buf;
int nr = 0;
using (var fs = new FileStream(fiTracker.FullName, FileMode.Open, FileAccess.Read, FileShare.Read, 16384, true))
{
// TODO: implement an async buffered Stream:
buf = new byte[16384];
nr = await fs.ReadAsync(buf, 0, 16384).ConfigureAwait(continueOnCapturedContext: false);
if (nr >= 16384)
{
// My, what a large tag you have!
throw new NotSupportedException();
}
}
// Parse the CommitID:
using (var ms = new MemoryStream(buf, 0, nr, false))
using (var sr = new StreamReader(ms, Encoding.UTF8))
{
string line = sr.ReadLine();
if (line == null) return new RefNameDoesNotExistError(refName);
var ecid = CommitID.TryParse(line);
if (ecid.HasErrors) return ecid.Errors;
return (Ref)new Ref.Builder(refName, ecid.Value);
}
}
示例3: GetPointsArrayAsync
private static async Task<JArray> GetPointsArrayAsync(string path)
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 4096, useAsync: true);
try
{
StringBuilder sb = new StringBuilder();
byte[] buffer = new byte[0x1000];
int numRead;
while ((numRead = await fs.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
string text = Encoding.Unicode.GetString(buffer, 0, numRead);
sb.Append(text);
}
return JArray.Parse(sb.ToString());
}
catch (IOException e) when (e.HResult == 0x01)
{
}
finally
{
}
return new JArray();
}
示例4: CopyAsync
private static void CopyAsync(byte[] buffer, FileStream inputStream, Stream outputStream, TaskCompletionSource<object> tcs)
{
inputStream.ReadAsync(buffer).Then(read =>
{
if (read > 0)
{
outputStream.WriteAsync(buffer, 0, read)
.Then(() => CopyAsync(buffer, inputStream, outputStream, tcs))
.Catch(ex =>
{
inputStream.Close();
outputStream.Close();
tcs.SetException(ex);
});
}
else
{
inputStream.Close();
outputStream.Close();
tcs.SetResult(null);
}
})
.Catch(ex =>
{
inputStream.Close();
outputStream.Close();
tcs.SetException(ex);
});
}
示例5: 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;
}
}
示例6: read
public async Task<IEnumerable<string>> read()
{
string filePath = @"data/data.csv";
if (File.Exists(filePath) == false)
{
var emptyList = new List<string>();
Console.WriteLine("file not found: " + filePath);
return emptyList;
}
string data;
using (FileStream sourceStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 4096, useAsync: true))
{
StringBuilder sb = new StringBuilder();
byte[] buffer = new byte[0x1000];
int numRead;
while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
string text = Encoding.UTF8.GetString(buffer, 0, numRead);
sb.Append(text);
}
data = sb.ToString();
}
DateTime tempdate;
var lines = data.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None).Where(d => DateTime.TryParse(d.Split(',')[0], out tempdate));
return lines;
}
示例7: StabilizeVideo
// -----------------------------------------------------------------------
// KEY SAMPLE CODE STARTS HERE
// -----------------------------------------------------------------------
private async Task StabilizeVideo(string subscriptionKey, string originalFilePath)
{
_dataContext.IsWorking = true;
_dataContext.SourceUri = null;
_dataContext.ResultUri = null;
Helpers.Log(LogIdentifier, "Start stabilizing");
Microsoft.ProjectOxford.Video.VideoServiceClient client =
new Microsoft.ProjectOxford.Video.VideoServiceClient(subscriptionKey);
using (FileStream originalStream = new FileStream(originalFilePath, FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[originalStream.Length];
await originalStream.ReadAsync(bytes, 0, (int) originalStream.Length);
// Creates a video operation of video stabilization
Helpers.Log(LogIdentifier, "Start uploading video");
Operation operation = await client.CreateOperationAsync(bytes, OperationType.Stabilize);
Helpers.Log(LogIdentifier, "Uploading video done");
// Starts querying service status
OperationResult result = await client.GetOperationResultAsync(operation);
while (result.Status != OperationStatus.Succeeded && result.Status != OperationStatus.Failed)
{
Helpers.Log(LogIdentifier, "Server status: {0}, wait {1} seconds...", result.Status, QueryWaitTime.TotalSeconds);
await Task.Delay(QueryWaitTime);
result = await client.GetOperationResultAsync(operation);
}
Helpers.Log(LogIdentifier, "Finish processing with server status: " + result.Status);
// Processing finished, checks result
if (result.Status == OperationStatus.Succeeded)
{
// Downloads generated video
string tmpFilePath = Path.GetTempFileName() + Path.GetExtension(originalFilePath);
Helpers.Log(LogIdentifier, "Start downloading result video");
using (Stream resultStream = await client.GetResultVideoAsync(result.ResourceLocation))
using (FileStream stream = new FileStream(tmpFilePath, FileMode.Create))
{
byte[] b = new byte[2048];
int length = 0;
while ((length = await resultStream.ReadAsync(b, 0, b.Length)) > 0)
{
await stream.WriteAsync(b, 0, length);
}
}
Helpers.Log(LogIdentifier, "Downloading result video done");
_dataContext.SourceUri = new Uri(originalFilePath);
_dataContext.ResultUri = new Uri(tmpFilePath);
}
else
{
// Failed
Helpers.Log(LogIdentifier, "Fail reason: " + result.Message);
}
_dataContext.IsWorking = false;
}
}
示例8: 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 + " %";
}));
}
}
}
}
示例9: ReadFileAsync
private static async Task ReadFileAsync(RetryContext context)
{
try
{
using (FileStream stream = new FileStream("test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 256, true))
{
byte[] buffer = new byte[4];
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead == buffer.Length)
{
string text = Encoding.ASCII.GetString(buffer);
Log("ReadFileAsync read '{0}'", text);
context.Add("Text", text);
}
else
{
Log("ReadFileAsync read only {0} bytes.", bytesRead);
}
}
}
catch (Exception e)
{
Log("ReadFileAsync error: {0}: {1}", e.GetType().Name, e.Message);
throw;
}
}
示例10: ReadAsync
public async Task<byte[]> ReadAsync() {
using (var input = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) {
var result = new byte[input.Length];
await input.ReadAsync(result, 0, (int)input.Length);
return result;
}
}
示例11: WritePlayerStat
public static async void WritePlayerStat(VehicleHash hash, int data)
{
string str = encrypt(string.Format("{0}>{1}", (int)hash, data));
using (var fstream = new FileStream("scripts\\driftstats.stat", FileMode.OpenOrCreate))
{
int seekPos = 0;
byte[] buffer = new byte[24];
while (seekPos < fstream.Length)
{
fstream.Seek(seekPos, SeekOrigin.Begin);
await fstream.ReadAsync(buffer, 0, 24);
var line = decrypt(Encoding.ASCII.GetString(buffer));
var keyVal = line.Substring(0, line.IndexOf('>'));
var value = line.Substring(line.IndexOf('>') + 1);
if (keyVal == ((int)hash).ToString())
{
using (StreamWriter writer = new StreamWriter(fstream))
{
writer.BaseStream.Seek(seekPos, SeekOrigin.Begin);
writer.BaseStream.Write(Encoding.ASCII.GetBytes(str), 0, 24);
}
return;
}
seekPos += 24;
}
}
using (StreamWriter writer = File.AppendText("scripts\\driftstats.stat"))
{
if (writer.BaseStream.CanWrite)
writer.Write(str);
}
}
示例12: NullBufferThrows
public void NullBufferThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
Assert.Throws<ArgumentNullException>("buffer", () =>
FSAssert.CompletesSynchronously(fs.ReadAsync(null, 0, 1)));
}
}
示例13: GetPhotoInBytes
public async Task<byte[]> GetPhotoInBytes(string photoPath) {
byte[] photo;
using (var fs = new FileStream(photoPath, FileMode.Open)) {
photo = new byte[fs.Length];
await fs.ReadAsync(photo, 0, photo.Length);
}
return photo;
}
示例14: ReadAllBytesAsync
public static async Task<byte[]> ReadAllBytesAsync(string Path)
{
using (var file = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
{
byte[] buff = new byte[file.Length];
await file.ReadAsync(buff, 0, (int)file.Length).ConfigureAwait(false);
return buff;
}
}
示例15: ReadStreamAsync
private async Task<MemoryStream> ReadStreamAsync(FileStream stream, CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(stream.Position == 0);
byte[] buffer = new byte[(int)stream.Length];
await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
// publiclyVisible must be true to enable optimizations in Roslyn.Compilers.TextUtilities.DetectEncodingAndDecode
return new MemoryStream(buffer, index: 0, count: buffer.Length, writable: false, publiclyVisible: true);
}