本文整理汇总了C#中System.IO.FileStream.EndWrite方法的典型用法代码示例。如果您正苦于以下问题:C# FileStream.EndWrite方法的具体用法?C# FileStream.EndWrite怎么用?C# FileStream.EndWrite使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.FileStream
的用法示例。
在下文中一共展示了FileStream.EndWrite方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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();
}
示例2: 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();
}
示例3: EndWriteThrowsForNullAsyncResult
public void EndWriteThrowsForNullAsyncResult()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite))
{
Assert.Throws<ArgumentNullException>("asyncResult", () => fs.EndWrite(null));
}
}
示例4: 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);
}
示例5: Main
static void Main(string[] args)
{
int max = 5000000;
Stopwatch sw = Stopwatch.StartNew();
Console.WriteLine(sw.Elapsed + " start calculating sinuses");
var sins = string.Join("\r\n",
Enumerable.Range(0, max)
.AsParallel()
.Select(x => new {x, sinX=Math.Sin(x)})
.Where(pair => pair.sinX > 0)
.OrderBy(pair => pair.sinX)
.Select(pair => pair.ToString()));
byte[] data = Encoding.ASCII.GetBytes(sins);
Console.WriteLine(sw.Elapsed + " start writing sinuses");
var fs = new FileStream("sins.txt",
FileMode.Create, FileAccess.Write, FileShare.None, 4096,
FileOptions.WriteThrough
| FileOptions.Asynchronous
);
// fs.Write(data, 0, data.Length);
// Console.WriteLine(sw.Elapsed + " sinuses written!");
fs.BeginWrite(data, 0, data.Length, res =>
{
Console.WriteLine(sw.Elapsed + " sinuses written!");
fs.EndWrite(res);
fs.Dispose();
data = null;
}, null);
// Console.WriteLine(sw.Elapsed + " start calculating cosinuses");
// var coses = Enumerable.Range(0, max)
// .AsParallel()
// .Select(x => new { x, cosX = Math.Cos(x) })
// .Where(pair => pair.cosX > 0)
// .OrderBy(pair => pair.cosX)
// .Select(pair => pair.ToString());
// Console.WriteLine(sw.Elapsed + " start writing cosinuses");
// var cosinuses = string.Join("\r\n", coses);
// File.WriteAllText("cosinuses.txt", cosinuses);
// Console.WriteLine(sw.Elapsed);
}
示例6: BeginWrite_Disposed
public void BeginWrite_Disposed ()
{
string path = TempFolder + Path.DirectorySeparatorChar + "temp";
DeleteFile (path);
FileStream stream = new FileStream (path, FileMode.OpenOrCreate, FileAccess.Write);
stream.Close ();
stream.EndWrite (stream.BeginWrite (new byte[8], 0, 8, null, null));
}
示例7: _subscriber_OnReceiveMessageEventHandler
void _subscriber_OnReceiveMessageEventHandler(object obj)
{
if (obj == null)
{
AddToTextBox("收到为空的信息");
return;
}
if (obj is string)
{
AddToTextBox(obj.ToString());
}
else if (obj is DateTime)
{
AddToTextBox(((DateTime)obj).ToString(CultureInfo.InvariantCulture));
}
else
{
if (obj is byte[])
{
string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
string.Format("{0}.jpg", DateTime.Now.ToString("yyyy_MM-dd_hh_mm_ss")));
FileStream writer = new FileStream(fileName, FileMode.OpenOrCreate);
byte[] buffer = (byte[])(obj);
writer.BeginWrite(buffer, 0, buffer.Length, delegate(IAsyncResult result)
{
writer.EndWrite(result);
InvokeTextBox(this.sendInfoRtb, string.Format("接收文件读写完成,共{0}", buffer.Length));
writer.Close();
}, null);
this.AddToTextBox(string.Format("接受到文件"));
}
}
}
示例8: DoSequentialWrite
private void DoSequentialWrite(
BlobTransferContext transferContext,
FileStream stream)
{
if (transferContext.CancellationToken.IsCancellationRequested)
{
return;
}
byte[] buffer = null;
if (transferContext.BlocksForFileIO.TryGetValue(transferContext.NextFileIOBlock, out buffer) && buffer != null)
{
transferContext.IsReadingOrWriting = true;
long endOfRange = transferContext.Length + transferContext.InitialOffset;
long beginFilePosition = (long)transferContext.NextFileIOBlock * transferContext.BlockSize + transferContext.InitialOffset;
beginFilePosition = beginFilePosition > endOfRange
? endOfRange
: beginFilePosition;
long nextBeginFilePosition = (transferContext.NextFileIOBlock + 1) * (long)transferContext.BlockSize + transferContext.InitialOffset;
nextBeginFilePosition = nextBeginFilePosition > endOfRange
? endOfRange
: nextBeginFilePosition;
int bytesToWrite = (int)(nextBeginFilePosition - beginFilePosition);
ApplyEncryptionTransform(transferContext.FileEncryption, transferContext.InitializationVector, beginFilePosition, buffer, bytesToWrite);
stream.BeginWrite(
buffer,
0,
bytesToWrite,
result3 =>
{
SuccessfulOrRetryableResult wasWriteSuccessful =
IsActionSuccessfulOrRetryable(transferContext, () => stream.EndWrite(result3));
transferContext.MemoryManager.ReleaseBuffer(buffer);
if (!wasWriteSuccessful.IsSuccessful)
{
transferContext.IsReadingOrWriting = false;
return;
}
transferContext.NextFileIOBlock++;
Interlocked.Add(ref transferContext.BytesWrittenOrReadToFile, bytesToWrite);
InvokeProgressCallback(transferContext, transferContext.BytesWrittenOrReadToFile, bytesToWrite);
transferContext.IsReadingOrWriting = false;
if (transferContext.BytesWrittenOrReadToFile >= transferContext.Length)
{
transferContext.IsComplete = true;
transferContext.OnComplete();
}
},
null);
}
}
示例9: UploadFile
public void UploadFile(CustomFileInfo currentUploadFile)
{
try
{
logger.Info("Begin to writer file...");
if (!Directory.Exists(MediaConfiguration.StoragePath))
{
Directory.CreateDirectory(MediaConfiguration.StoragePath);
}
var fs = new FileStream(MediaConfiguration.StoragePath + "\\" + currentUploadFile.FileName,
FileMode.OpenOrCreate, FileAccess.Write);
fs.Seek(currentUploadFile.CurrentOffset, SeekOrigin.Begin);
fs.BeginWrite(
currentUploadFile.CurrentData, 0,
currentUploadFile.CurrentLen,
delegate(IAsyncResult ra)
{
fs.EndWrite(ra);
fs.Close();
fs.Dispose();
}, null);
}
catch (Exception e)
{
logger.Error("Error occurred when writing file, details: {0}.", e);
}
}
示例10: UploadChunk
public void UploadChunk(ChunkInfo chunkInfo)
{
try
{
var fs = new FileStream(MediaConfiguration.StoragePath
+ "\\" + chunkInfo.StrongChecksum,
FileMode.OpenOrCreate, FileAccess.Write);
fs.BeginWrite(
chunkInfo.Buffer, 0,
chunkInfo.BufferLength,
delegate(IAsyncResult ra)
{
try
{
fs.EndWrite(ra);
fs.Close();
fs.Dispose();
fs = null;
MediaIndexOperator.GetIndexDatabaseHelper()
.ExecuteNonQuery(new List<ChunkPathMap>
{
new ChunkPathMap
{
ChunkId = chunkInfo.Id,
Path = MediaConfiguration.StoragePath
}
});
}
catch (Exception e)
{
logger.Error("Error occurred when uploading chunk, " +
"details: {0}.", e);
}
}, null);
}
catch (Exception e)
{
logger.Error("Error occurred when writing file, details: {0}.",
e);
}
finally
{
MediaConfiguration.MediaControl.MediaControlProxy
.CompleteSession(MediaConfiguration.CurrrentMedia.Id);
}
}
示例11: SampleAsyncMethods
private static void SampleAsyncMethods()
{
IAsyncResult asyncResult;
/***** SQL Connection *****/
// NOTE: "Async=true" setting required for asynchronous operations.
using (SqlConnection connection = new SqlConnection(@"Async=true;Server=SERVER;Database=DATABASE;Integrated Security=true"))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("SELECT UserId, Name, LastLogIn FROM Users WHERE Email = '[email protected]'", connection))
{
asyncResult = cmd.BeginExecuteReader();
// ... query executes asynchronously in background ...
using (IDataReader reader = cmd.EndExecuteReader(asyncResult))
{
// WARNING: The DbAsyncResult object returned by BeginExecuteReader always creates a ManualResetEvent, but
// never closes it; after calling EndExecuteReader, the AsyncWaitHandle property is still valid, so we close it explicitly.
asyncResult.AsyncWaitHandle.Close();
while (reader.Read())
{
// do stuff
}
}
}
using (SqlCommand cmd = new SqlCommand("UPDATE Users SET LastLogIn = GETUTCDATE() WHERE UserId = 1", connection))
{
asyncResult = cmd.BeginExecuteNonQuery();
// ... query executes asynchronously in background ...
int rowsAffected = cmd.EndExecuteNonQuery(asyncResult);
// WARNING: The DbAsyncResult object returned by BeginExecuteNonQuery always creates a ManualResetEvent, but
// never closes it; after calling EndExecuteReader, the AsyncWaitHandle property is still valid, so we close it explicitly.
asyncResult.AsyncWaitHandle.Close();
}
}
/***** File Operations *****/
// NOTE: FileOptions.Asynchronous flag required for asynchronous operations.
using (Stream stream = new FileStream(@"C:\Temp\test.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096,
FileOptions.Asynchronous))
{
byte[] buffer = new byte[65536];
asyncResult = stream.BeginRead(buffer, 0, buffer.Length, null, null);
// ... disk read executes asynchronously in background ...
int bytesRead = stream.EndRead(asyncResult);
}
/***** HTTP Operation *****/
// WARNING: DNS operations are synchronous, and will block!
WebRequest request = WebRequest.Create(new Uri(@"http://www.example.com/sample/page"));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
asyncResult = request.BeginGetRequestStream(null, null);
// ... connection to server opened in background ...
using (Stream stream = request.EndGetRequestStream(asyncResult))
{
byte[] bytes = Encoding.UTF8.GetBytes("Sample request");
asyncResult = stream.BeginWrite(bytes, 0, bytes.Length, null, null);
stream.EndWrite(asyncResult);
}
// WARNING: WebRequest will swallow any exceptions thrown from the AsyncCallback passed to BeginGetResponse.
asyncResult = request.BeginGetResponse(null, null);
// ... web request executes in background ...
using (WebResponse response = request.EndGetResponse(asyncResult))
using (Stream stream = response.GetResponseStream())
{
// read response from server
// WARNING: This code should also use asynchronous operations (BeginRead, EndRead); "Using synchronous calls
// in asynchronous callback methods can result in severe performance penalties." (MSDN)
}
/***** DNS hostname resolution *****/
// WARNING: Doesn't truly use async I/O, but simply queues the request to a ThreadPool thread.
asyncResult = Dns.BeginGetHostEntry("www.example.com", null, null);
// ... DNS lookup executes in background
IPHostEntry entry = Dns.EndGetHostEntry(asyncResult);
/***** Other: Sockets, Serial Ports, SslStream *****/
}
示例12: Copy
/// <summary>
/// Copies the specified source file to the specified destination file, overwriting if it exists.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="destination">The destination.</param>
public static void Copy(string source, string destination)
{
var bufferLength = 4 * 1024 * 32;
var readBuffer = new Byte[bufferLength];
var writeBuffer = new Byte[bufferLength];
var readSize = -1;
IAsyncResult writeResult;
IAsyncResult readResult;
using (var sourceStream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.None, 8, FileOptions.Asynchronous | FileOptions.SequentialScan))
using (var destinationStream = new FileStream(destination, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 8, FileOptions.Asynchronous | FileOptions.SequentialScan))
{
destinationStream.SetLength(sourceStream.Length);
readSize = sourceStream.Read(readBuffer, 0, readBuffer.Length);
readBuffer = Interlocked.Exchange(ref writeBuffer, readBuffer);
while (readSize > 0)
{
writeResult = destinationStream.BeginWrite(writeBuffer, 0, readSize, null, null);
readResult = sourceStream.BeginRead(readBuffer, 0, readBuffer.Length, null, null);
destinationStream.EndWrite(writeResult);
readSize = sourceStream.EndRead(readResult);
readBuffer = Interlocked.Exchange(ref writeBuffer, readBuffer);
}
sourceStream.Close();
destinationStream.Close();
}
}
示例13: GetEnumerator
public override IEnumerator<CoroutineState> GetEnumerator()
{
FileStream fileReader = new FileStream(
_fileName,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
BUFFER_SIZE,
true);
FileStream fileWriter = new FileStream(
Path.Combine(_destinationFolder, Path.GetFileName(_fileName)),
FileMode.Create,
FileAccess.ReadWrite,
FileShare.Write,
BUFFER_SIZE,
true);
int bytesRead = 0;
do
{
//Read asynchronously
bool finishedRead = false;
IAsyncResult readResult = fileReader.BeginRead(_buffer, 0, BUFFER_SIZE,
(asyncResult) =>
{
bytesRead = fileReader.EndRead(asyncResult);
finishedRead = true;
},
null);
//Wait until the reading is complete
while (!finishedRead)
{
//Allow other coroutines to run
yield return CoroutineState.Running;
}
Console.WriteLine("Finished reading chunk for: " + _fileName);
//Write asynchronously
bool finishedWriting = false;
IAsyncResult writeResult = fileWriter.BeginWrite(_buffer, 0, bytesRead,
(asyncResult) =>
{
fileWriter.EndWrite(asyncResult);
finishedWriting = true;
},
null);
//Wait until write is finished
while (!finishedWriting)
{
//Let other coroutines run
yield return CoroutineState.Running;
}
Console.WriteLine("Finished writing chunk for: " + _fileName);
} while (bytesRead > 0);
fileReader.Close();
fileWriter.Close();
}