本文整理汇总了C#中System.IO.FileStream.EndRead方法的典型用法代码示例。如果您正苦于以下问题:C# FileStream.EndRead方法的具体用法?C# FileStream.EndRead怎么用?C# FileStream.EndRead使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.FileStream
的用法示例。
在下文中一共展示了FileStream.EndRead方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
//AsyncReadOneFile();
//AsyncReadMultiplyFiles();
FileStream fs = new FileStream(@"../../Program.cs", FileMode.Open,
FileAccess.Read, FileShare.Read, 1024,
FileOptions.Asynchronous);
Byte[] data = new Byte[100];
IAsyncResult ar = fs.BeginRead(data, 0, data.Length, null, null);
while (!ar.IsCompleted)
{
Console.WriteLine("Операция не завершена, ожидайте...");
Thread.Sleep(10);
}
Int32 bytesRead = fs.EndRead(ar);
fs.Close();
Console.WriteLine("Количество считаных байт = {0}", bytesRead);
Console.WriteLine(Encoding.UTF8.GetString(data).Remove(0, 1));
}
示例2: AsyncReadOneFileCallBackAnonimus
private static void AsyncReadOneFileCallBackAnonimus()
{
Byte[] data = new Byte[100];
Console.WriteLine("Основной поток ID = {0}",
Thread.CurrentThread.ManagedThreadId);
FileStream fs = new FileStream(@"../../Program.cs", FileMode.Open,
FileAccess.Read, FileShare.Read, 1024,
FileOptions.Asynchronous);
fs.BeginRead(data, 0, data.Length, delegate(IAsyncResult ar)
{
Console.WriteLine("Чтение в потоке {0} закончено",
Thread.CurrentThread.ManagedThreadId);
Int32 bytesRead = fs.EndRead(ar);
fs.Close();
Console.WriteLine("Количество считаных байт = {0}", bytesRead);
Console.WriteLine(Encoding.UTF8.GetString(data).Remove(0, 1));
Console.ReadLine();
}, null);
Console.ReadLine();
}
示例3: Main
static void Main(string[] args)
{
// open filestream for asynchronous read
FileStream fs = new FileStream("somedata.dat", FileMode.Open,
FileAccess.Read, FileShare.Read, 1024,
FileOptions.Asynchronous);
// byte array to hold 100 bytes of data
Byte[] data = new Byte[100];
// initiate asynchronous read operation, reading first 100 bytes
IAsyncResult ar = fs.BeginRead(data, 0, data.Length, null, null);
// could do something in here which would run alongside file read...
// check for file read complete
while (!ar.IsCompleted)
{
Console.WriteLine("Operation not completed");
Thread.Sleep(10);
}
// get the result
int bytesRead = fs.EndRead(ar);
fs.Close();
Console.WriteLine("Number of bytes read={0}", bytesRead);
Console.WriteLine(BitConverter.ToString(data, 0, bytesRead));
}
示例4: EndReadThrowsForNullAsyncResult
public void EndReadThrowsForNullAsyncResult()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite))
{
Assert.Throws<ArgumentNullException>("asyncResult", () => fs.EndRead(null));
}
}
示例5: APMWithFiles
/// <summary>
/// Demonstrates the use of the APM with files, through the FileStream class.
/// This method performs asynchronous reads and writes to copy data from an input
/// file to an output file. Reads and writes are interlaced, and proceed in chunks
/// of 8KB at a time (displaying progress to the console).
/// </summary>
static void APMWithFiles()
{
FileStream reader = new FileStream("sample.txt", FileMode.Open);
FileStream writer = new FileStream("sample2.txt", FileMode.Create);
byte[] buffer1 = new byte[8192], buffer2 = new byte[8192];
IAsyncResult ar1, ar2 = null;
while (true)
{
ar1 = reader.BeginRead(buffer1, 0, buffer1.Length, null, null);
while (!ar1.IsCompleted)
{
Console.Write("R");
}
if (ar2 != null)
{
while (!ar2.IsCompleted)
{
Console.Write("W");
}
}
int bytesRead;
if ((bytesRead = reader.EndRead(ar1)) == 0)
break; //No more data to read
if (ar2 != null)
{
writer.EndWrite(ar2);
}
Array.Copy(buffer1, buffer2, bytesRead);
ar2 = writer.BeginWrite(buffer2, 0, bytesRead, null, null);
}
Console.WriteLine();
Console.WriteLine();
}
示例6: ApplyIPSPatch
public static void ApplyIPSPatch(string romname, string patchname)
{
// Noobish Noobsicle wrote this IPS patching code
// romname is the original ROM, patchname is the patch to apply
FileStream romstream = new FileStream(romname, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
FileStream ipsstream = new FileStream(patchname, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
int lint = (int)ipsstream.Length;
byte[] ipsbyte = new byte[ipsstream.Length];
byte[] rombyte = new byte[romstream.Length];
IAsyncResult romresult;
IAsyncResult ipsresult = ipsstream.BeginRead(ipsbyte, 0, lint, null, null);
ipsstream.EndRead(ipsresult);
int ipson = 5;
int totalrepeats = 0;
int offset = 0;
bool keepgoing = true;
while (keepgoing == true)
{
offset = ipsbyte[ipson] * 0x10000 + ipsbyte[ipson + 1] * 0x100 + ipsbyte[ipson + 2];
ipson++;
ipson++;
ipson++;
if (ipsbyte[ipson] * 256 + ipsbyte[ipson + 1] == 0)
{
ipson++;
ipson++;
totalrepeats = ipsbyte[ipson] * 256 + ipsbyte[ipson + 1];
ipson++;
ipson++;
byte[] repeatbyte = new byte[totalrepeats];
for (int ontime = 0; ontime < totalrepeats; ontime++)
repeatbyte[ontime] = ipsbyte[ipson];
romstream.Seek(offset, SeekOrigin.Begin);
romresult = romstream.BeginWrite(repeatbyte, 0, totalrepeats, null, null);
romstream.EndWrite(romresult);
ipson++;
}
else
{
totalrepeats = ipsbyte[ipson] * 256 + ipsbyte[ipson + 1];
ipson++;
ipson++;
romstream.Seek(offset, SeekOrigin.Begin);
romresult = romstream.BeginWrite(ipsbyte, ipson, totalrepeats, null, null);
romstream.EndWrite(romresult);
ipson = ipson + totalrepeats;
}
if (ipsbyte[ipson] == 69 && ipsbyte[ipson + 1] == 79 && ipsbyte[ipson + 2] == 70)
keepgoing = false;
}
romstream.Close();
ipsstream.Close();
}
示例7: Main
static void Main(string[] args)
{
byte[] buf = new byte[128];
FileStream file = new FileStream(@"D:\hello.py", FileMode.Open);
IAsyncResult ar = file.BeginRead(buf, 0, 128, null, null);
Thread.Sleep(1000); // do other things
int n = file.EndRead(ar);
file.Close();
string s = Encoding.UTF8.GetString(buf, 0, n);
Console.WriteLine("Readed: {0}, {1}", n, s);
}
示例8: DemoAsync
static void DemoAsync()
{
using (var fs = new FileStream(@"C:\temp\foo.txt", FileMode.Open))
{
byte[] content = new byte[fs.Length];
IAsyncResult ar = fs.BeginRead(content, 0, (int)fs.Length, ReadCompletionCallback, null);
Console.WriteLine("控制流程回到主執行緒,執行其他工作...");
Thread.Sleep(1500); // 模擬執行其他工作需要花費的時間。
// 等到需要取得結果時,呼叫 EndRead 方法(會 block 當前執行緒)
int bytesRead = fs.EndRead(ar);
Console.WriteLine("一共讀取了 {0} bytes。", bytesRead);
}
}
示例9: AsyncReadOneFile
//Метод считывания из одного файла
private static void AsyncReadOneFile()
{
FileStream fs = new FileStream(@"../../Program.cs", FileMode.Open, FileAccess.Read,
FileShare.Read, 1024, FileOptions.Asynchronous);
Byte[] data = new Byte[100];
// Начало асинхронной операции чтения из файла FileStream.
IAsyncResult ar = fs.BeginRead(data, 0, data.Length, null, null);
// Здесь выполняется другой код...
// Приостановка этого потока до завершения асинхронной операции
// и получения ее результата.
Int32 bytesRead = fs.EndRead(ar);
// Других операций нет. Закрытие файла.
fs.Close();
// Теперь можно обратиться к байтовому массиву и вывести результат операции.
Console.WriteLine("Количество прочитаных байт = {0}", bytesRead);
Console.WriteLine(Encoding.UTF8.GetString(data).Remove(0, 1));
}
示例10: CopyFile
public static void CopyFile(String sourcePath, String destinationPath, Action<String, String, Exception> completed)
{
Stream source = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
Stream destination = new FileStream(destinationPath, FileMode.Create, FileAccess.Write);
byte[] buffer = new byte[0x1000];
AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(null);
Action<Exception> cbCompleted = e =>
{
if (completed != null) asyncOp.Post(delegate
{
source.Close();
destination.Close();
completed(sourcePath, destinationPath, e);
}, null);
};
AsyncCallback rc = null;
rc = readResult =>
{
try
{
int read = source.EndRead(readResult);
if (read > 0)
{
destination.BeginWrite(buffer, 0, read, writeResult =>
{
try
{
destination.EndWrite(writeResult);
source.BeginRead(
buffer, 0, buffer.Length, rc, null);
}
catch (Exception exc) { cbCompleted(exc); }
}, null);
}
else cbCompleted(null);
}
catch (Exception exc) { cbCompleted(exc); }
};
source.BeginRead(buffer, 0, buffer.Length, rc, null);
}
示例11: BeginRead_Disposed
public void BeginRead_Disposed ()
{
string path = TempFolder + Path.DirectorySeparatorChar + "temp";
DeleteFile (path);
FileStream stream = new FileStream (path, FileMode.OpenOrCreate, FileAccess.Read);
stream.Close ();
stream.EndRead (stream.BeginRead (new byte[8], 0, 8, null, null));
}
示例12: read
// len, buf, err
public static void read(FileStream fd, byte[] buffer, long offset, long length, Action<int, byte[], Exception> callback)
{
try
{
fd.BeginRead(buffer, (int)offset, (int)length, ar =>
{
try
{
int len = fd.EndRead(ar);
Boundary.Instance.ExecuteOnTargetLoop( () => callback( len, buffer, null ));
} catch (Exception e){
Boundary.Instance.ExecuteOnTargetLoop( () => callback( 0, buffer, null ));
}
}, null);
}
catch (Exception e)
{
callback(0, buffer, e);
}
}
示例13: DoSequentialRead
private void DoSequentialRead(
BlobTransferContext transferContext,
FileStream stream,
byte[] streamBuffer = null,
KeyValuePair<long, int>? inputStartAndLength = null)
{
if (transferContext.CancellationToken.IsCancellationRequested)
{
return;
}
if (streamBuffer == null)
{
streamBuffer = transferContext.MemoryManager.RequireBuffer();
}
if (streamBuffer == null)
{
return;
}
KeyValuePair<long, int> startAndLength;
if (inputStartAndLength == null)
{
if (!transferContext.BlocksToTransfer.TryDequeue(out startAndLength))
{
transferContext.MemoryManager.ReleaseBuffer(streamBuffer);
return;
}
}
else
{
startAndLength = inputStartAndLength.Value;
}
// Catch any exceptions and cleanup the buffer. Otherwise uncleaned buffers will result in hang for future
// uploads as memorymanager is being shared.
// Also mark the transfer as complete and add exceptions to the transfercontext exception list.
try
{
if (!transferContext.PartialFileIOState.ContainsKey(startAndLength.Key))
{
transferContext.PartialFileIOState[startAndLength.Key] = 0;
}
transferContext.IsReadingOrWriting = true;
long beginFilePosition = startAndLength.Key;
long nextBeginFilePosition = startAndLength.Key + transferContext.BlockSize;
nextBeginFilePosition =
nextBeginFilePosition > transferContext.Length
? transferContext.Length
: nextBeginFilePosition;
beginFilePosition = beginFilePosition + transferContext.PartialFileIOState[startAndLength.Key];
int bytesToRead = (int)(nextBeginFilePosition - beginFilePosition);
stream.BeginRead(
streamBuffer,
transferContext.PartialFileIOState[startAndLength.Key],
bytesToRead,
result3 =>
{
int bytesRead;
SuccessfulOrRetryableResult wasReadSuccessful =
IsActionSuccessfulOrRetryable(transferContext, () => stream.EndRead(result3), out bytesRead);
if (!wasReadSuccessful.IsSuccessful)
{
transferContext.IsReadingOrWriting = false;
transferContext.MemoryManager.ReleaseBuffer(streamBuffer);
}
else if (bytesRead != bytesToRead)
{
transferContext.PartialFileIOState[startAndLength.Key] += bytesRead;
DoSequentialRead(transferContext, stream, streamBuffer, startAndLength);
}
else
{
transferContext.IsReadingOrWriting = false;
ApplyEncryptionTransform(
transferContext.FileEncryption,
Path.GetFileName(transferContext.LocalFilePath),
beginFilePosition,
streamBuffer,
bytesToRead);
transferContext.BlocksForFileIO[(int)(startAndLength.Key / transferContext.BlockSize)] = streamBuffer;
}
},
null);
}
catch (Exception ex)
{
transferContext.IsComplete = true;
//.........这里部分代码省略.........
示例14: ExtendFile
internal UInt64 ExtendFile(UInt64 fp, string filename)
{
int size = 65536 * 4;
byte[] readBuf = new byte[size];
byte[] fpBuf = new byte[size];
ulong fileFP = fp;
using (Stream ifs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, size, FileOptions.Asynchronous | FileOptions.SequentialScan))
{
IAsyncResult readResult = ifs.BeginRead(readBuf, 0, readBuf.Length, null, null);
while (true)
{
int bytesRead = ifs.EndRead(readResult);
if (bytesRead == 0) break;
byte[] tmpBuf = fpBuf;
fpBuf = readBuf;
readBuf = tmpBuf;
readResult = ifs.BeginRead(readBuf, 0, readBuf.Length, null, null);
fileFP = this.Extend(fileFP, fpBuf, 0, bytesRead);
}
}
return fileFP;
}
示例15: AsyncRead
//使用FileStream对象的BeginRead()方法
void AsyncRead()
{
FileStream fs = new FileStream(Server.MapPath("/UTF8Text.txt"), FileMode.Open, FileAccess.Read, FileShare.None, 4096, FileOptions.Asynchronous);
fs.Seek(0, SeekOrigin.Begin);
byte[] buffer = new byte[100];
//开始异步读操作
IAsyncResult ar = fs.BeginRead(buffer, 0, buffer.Length, null, null);
while (!ar.AsyncWaitHandle.WaitOne(10, false))//直到异步读文件操作完成才退出轮询
{
}
int bytesRead = fs.EndRead(ar);//结束异步读操作
fs.Close();
string str = Encoding.Default.GetString(buffer, 0, buffer.Length);
Response.Write(str);
}