本文整理汇总了C#中Stream.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# Stream.Dispose方法的具体用法?C# Stream.Dispose怎么用?C# Stream.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Stream
的用法示例。
在下文中一共展示了Stream.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CompressResponse
/// <summary>
/// Compresses the response stream if the browser allows it.
/// </summary>
private static MemoryStream CompressResponse(Stream responseStream, HttpApplication app, string key)
{
MemoryStream dataStream = new MemoryStream();
StreamCopy(responseStream, dataStream);
responseStream.Dispose();
byte[] buffer = dataStream.ToArray();
dataStream.Dispose();
MemoryStream ms = new MemoryStream();
Stream compress = null;
if (IsEncodingAccepted(DEFLATE))
{
compress = new DeflateStream(ms, CompressionMode.Compress);
app.Application.Add(key + "enc", DEFLATE);
}
else if (IsEncodingAccepted(GZIP))
{
compress = new GZipStream(ms, CompressionMode.Compress);
app.Application.Add(key + "enc", DEFLATE);
}
compress.Write(buffer, 0, buffer.Length);
compress.Dispose();
return ms;
}
示例2: SaveXlsFileToTempLocation
/// <summary>
/// Save xls file to temp location in server
/// </summary>
/// <param name="fileInputStream">Stream Object</param>
/// <param name="xlsFilePath">xls file's path</param>
/// <returns>true if successful else false</returns>
private bool SaveXlsFileToTempLocation(Stream fileInputStream, string xlsFilePath)
{
bool isSaved = true;
try
{
int length = 256;
int bytesRead = 0;
Byte[] buffer = new Byte[length];
// write the required bytes
using (FileStream fs = new FileStream(xlsFilePath, FileMode.Create))
{
do
{
bytesRead = fileInputStream.Read(buffer, 0, length);
fs.Write(buffer, 0, bytesRead);
}
while (bytesRead == length);
}
fileInputStream.Dispose();
}
catch (Exception ex)
{
isSaved = false;
Global.CreateExceptionString(ex, null);
}
return isSaved;
}
示例3: setup
private void setup()
{
if (client == null || client.Connected == false)
{
try {
Debug.Log("trying to connect to " + host + ":" + port);
client = new TcpClient();
client.Connect(host, port);
if (stream != null)stream.Dispose();
stream = client.GetStream();
}
catch(Exception e)
{
Debug.LogError("network error: " + e.Message);
if (stream != null)stream.Dispose();
stream = null;
client = null;
}
}
}
示例4: PlayBobRoleAsync
private async Task PlayBobRoleAsync(ICryptographicKey ownSigningKey, ICryptographicKey othersSigningPublicKey, Stream channel, CancellationToken cancellationToken)
{
// Create ephemeral ECDH key pair, to prepare for the symmetric encryption key exchange.
using (var ecdhKeyPair = NetFxCrypto.ECDiffieHellman.Create())
{
// Send the ephemeral ECDH public key to Alice.
var ecdhPublicKey = ecdhKeyPair.PublicKey.ToByteArray();
await WriteAsync(channel, ecdhPublicKey, cancellationToken);
// Authenticate to Alice that this is really Bob's ephemeral public key.
byte[] ecdhPublicKeySignature = WinRTCrypto.CryptographicEngine.Sign(ownSigningKey, ecdhPublicKey);
await WriteAsync(channel, ecdhPublicKeySignature, cancellationToken);
// Read Alice's reply. It consists of her own ephemeral public key and signature.
byte[] alicePublicDH = await ReadAsync(channel, cancellationToken);
byte[] aliceSignedDH = await ReadAsync(channel, cancellationToken);
// Authenticate Alice's public key.
Assert.True(WinRTCrypto.CryptographicEngine.VerifySignature(othersSigningPublicKey, alicePublicDH, aliceSignedDH));
// Deserialize Alice's public key and derive the shared secret from it.
var aliceDHPK = NetFxCrypto.ECDiffieHellmanCngPublicKey.FromByteArray(alicePublicDH);
byte[] encryptionKeyMaterial = ecdhKeyPair.DeriveKeyMaterial(aliceDHPK);
var encryptionKey = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7)
.CreateSymmetricKey(encryptionKeyMaterial);
// Bob reads Alice's secret message using the shared secret that both parties derived,
// but never transmitted.
using (var aes = CryptoStream.ReadFrom(channel, WinRTCrypto.CryptographicEngine.CreateDecryptor(encryptionKey)))
{
byte[] plaintext = await ReadAsync(aes, cancellationToken);
// Assert that the plaintext is as it was expected to be.
CollectionAssertEx.AreEqual(SecretMessage, plaintext);
}
channel.Dispose();
}
}
示例5: PlayAliceRoleAsync
private async Task PlayAliceRoleAsync(ICryptographicKey ownSigningKey, ICryptographicKey othersSigningPublicKey, Stream channel, CancellationToken cancellationToken)
{
// Create ephemeral ECDH key pair, to prepare for the symmetric encryption key exchange.
using (var ecdhKeyPair = NetFxCrypto.ECDiffieHellman.Create())
{
// Alice receives Bob's ECDH public key and signature.
byte[] bobPublicDH = await ReadAsync(channel, cancellationToken);
byte[] bobSignedDH = await ReadAsync(channel, cancellationToken);
// Alice verifies Bob's signature to be sure it's his key.
Assert.True(WinRTCrypto.CryptographicEngine.VerifySignature(othersSigningPublicKey, bobPublicDH, bobSignedDH));
// Alice replies to Bob's public key by transmitting her own public key and signature.
var ecdhPublicKey = ecdhKeyPair.PublicKey.ToByteArray();
await WriteAsync(channel, ecdhPublicKey, cancellationToken);
byte[] ecdhPublicKeySignature = WinRTCrypto.CryptographicEngine.Sign(ownSigningKey, ecdhPublicKey);
await WriteAsync(channel, ecdhPublicKeySignature, cancellationToken);
// Derive a shared secret with Bob by combining Alice's private key with Bob's public key.
var bobDHPK = NetFxCrypto.ECDiffieHellmanCngPublicKey.FromByteArray(bobPublicDH);
byte[] encryptionKeyMaterial = ecdhKeyPair.DeriveKeyMaterial(bobDHPK);
var symmetricEncryptionKey = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7)
.CreateSymmetricKey(encryptionKeyMaterial);
// Alice also adds a secret message.
using (var aes = CryptoStream.WriteTo(channel, WinRTCrypto.CryptographicEngine.CreateEncryptor(symmetricEncryptionKey)))
{
await aes.WriteAsync(SecretMessage, 0, SecretMessage.Length, cancellationToken);
}
channel.Dispose();
}
}
示例6: CreateZip
private void CreateZip(Stream stream, ZipArchiveMode mode)
{
try {
if (mode != ZipArchiveMode.Read && mode != ZipArchiveMode.Create && mode != ZipArchiveMode.Update)
throw new ArgumentOutOfRangeException("mode");
// If the mode parameter is set to Read, the stream must support reading.
if (mode == ZipArchiveMode.Read && !stream.CanRead)
throw new ArgumentException("Stream must support reading for Read archive mode");
// If the mode parameter is set to Create, the stream must support writing.
if (mode == ZipArchiveMode.Create && !stream.CanWrite)
throw new ArgumentException("Stream must support writing for Create archive mode");
// If the mode parameter is set to Update, the stream must support reading, writing, and seeking.
if (mode == ZipArchiveMode.Update && (!stream.CanRead || !stream.CanWrite || !stream.CanSeek))
throw new ArgumentException("Stream must support reading, writing and seeking for Update archive mode");
try {
zipFile = mode != ZipArchiveMode.Create && stream.Length != 0
? SharpCompress.Archive.Zip.ZipArchive.Open(stream)
: SharpCompress.Archive.Zip.ZipArchive.Create();
} catch (Exception e) {
throw new InvalidDataException("The contents of the stream are not in the zip archive format.", e);
}
entries = new Dictionary<string, ZipArchiveEntry>();
if (Mode != ZipArchiveMode.Create) {
foreach (var entry in zipFile.Entries) {
var zipEntry = new ZipArchiveEntry(this, entry);
entries[entry.Key] = zipEntry;
}
}
}
catch {
if (!leaveStreamOpen)
stream.Dispose();
throw;
}
}
示例7: main
main(int argc, string []argv)
{
int s;
if (((argv[1][0] == '-') || (argv[1][0] == '-')) &&
((argv[1][1] == 'h') || (argv[1][1] == '?')))
{
Console.Out.WriteLine(
"This program is to make 'signatures' of known c library calls for the dcc " +
"program. It needs as the first arg the name of a library file, and as the " +
"second arg, the name of the signature file to be generated."
);
Environment.Exit(0);
}
if (argc <= 2)
{
Console.Out.WriteLine("Usage: makedsig <libname> <signame>\nor makedsig -h for help\n");
Environment.Exit(1);
}
try
{
f = new FileStream(argv[1], FileMode.Open);
}
catch
{
Console.WriteLine("Cannot read {0}", argv[1]);
Environment.Exit(2);
}
try
{
f2 = new FileStream(argv[2], FileMode.Create);
}
catch
{
Console.WriteLine("Cannot write {0}", argv[2]);
Environment.Exit(2);
}
Console.Error.Write("Seed: ");
s = Convert.ToInt32(Console.In.ReadLine());
var rnd = new Random(s);
numKeys = readSyms(); /* Read the keys (symbols) */
Console.WriteLine("Num keys: {0}; vertices: {1}", numKeys, (int)(numKeys*C));
hashParams( /* Set the parameters for the hash table */
numKeys, /* The number of symbols */
PATLEN, /* The length of the pattern to be hashed */
256, /* The character set of the pattern (0-FF) */
'\0', /* Minimum pattern character value */
(int)(numKeys*C)); /* C is the sparseness of the graph. See Czech,
Havas and Majewski for details */
/* The following two functions are in perfhlib.c */
map(); /* Perform the mapping. This will call
getKey() repeatedly */
assign(); /* Generate the function g */
saveFile(); /* Save the resultant information */
f.Dispose();
f2.Dispose();
}
示例8: DisposeStream
public void DisposeStream(ZipFileEntry _zfe, Stream s)
{
if (_zfe.Method == Compression.Deflate) s.Dispose();
}
示例9: Close
public void Close(Stream stream)
{
stream.Close();
stream.Dispose();
}
示例10: NegativeConsoleOutputTests
private static void NegativeConsoleOutputTests(Stream stream)
{
//ConsoleStream.Length should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => { long x = stream.Length; });
//ConsoleStream.get_Position should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => { long x = stream.Position; });
//ConsoleStream.set_Position should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => stream.Position = 50L);
//ConsoleStream.SetLength should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => stream.SetLength(50L));
// Flushing a stream is fine.
stream.Flush();
//Read and write methods
//ConsoleStream.Read(null) should throw ArgumentNullException
Assert.Throws<ArgumentNullException>(() => stream.Read(null, 0, 1));
//ConsoleStream.Read() should throw ArgumentOutOfRangeException
Assert.Throws<ArgumentOutOfRangeException>(() => stream.Read(new byte[] { 0, 1 }, -1, 0));
//ConsoleStream.Read() should throw ArgumentOutOfRangeException
Assert.Throws<ArgumentOutOfRangeException>(() => stream.Read(new byte[] { 0, 1 }, 0, -1));
//ConsoleStream.Read() should throw ArgumentException
Assert.Throws<ArgumentException>(() => stream.Read(new byte[] { 0, 1 }, 0, 50));
//ConsoleStream.Read() should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => stream.Read(new byte[] { 0, 1 }, 0, 2));
//ConsoleStream.Write() should throw ArgumentNullException
Assert.Throws<ArgumentNullException>(() => stream.Write(null, 0, 1));
//ConsoleStream.Write() should throw ArgumentOutOfRangeException
Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(new byte[] { 0, 1 }, -1, 0));
//ConsoleStream.Write() should throw ArgumentOutOfRangeException
Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(new byte[] { 0, 1 }, 0, -1));
//ConsoleStream.Write() should throw ArgumentException
Assert.Throws<ArgumentException>(() => stream.Write(new byte[] { 0, 1 }, 0, 50));
//ConsoleStream.Write() should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => stream.Seek(0L, SeekOrigin.Begin));
// Close the stream and make sure we can no longer read, write or flush
stream.Dispose();
//ConsoleStream.Read() should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => stream.Read(new byte[] { 0, 1 }, 0, 1));
//ConsoleStream.Write() should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => stream.Write(new byte[] { 0, 1 }, 0, 1));
//ConsoleStream.Flush() should throw NotSupportedException
Assert.Throws<ObjectDisposedException>(() => stream.Flush());
}
示例11: OpenInWriteMode
private Stream OpenInWriteMode()
{
if (_everOpenedForWrite)
throw new IOException(SR.CreateModeWriteOnceAndOneEntryAtATime);
//we assume that if another entry grabbed the archive stream, that it set this entry's _everOpenedForWrite property to true by calling WriteLocalFileHeaderIfNeeed
Debug.Assert(_archive.IsStillArchiveStreamOwner(this));
_everOpenedForWrite = true;
CheckSumAndSizeWriteStream crcSizeStream = GetDataCompressor(_archive.ArchiveStream, true,
(object o, EventArgs e) =>
{
//release the archive stream
_archive.ReleaseArchiveStream(this);
_outstandingWriteStream = null;
});
_outstandingWriteStream = new DirectToArchiveWriterStream(crcSizeStream, this);
return new WrappedStream(_outstandingWriteStream, (object o, EventArgs e) => _outstandingWriteStream.Dispose());
}
示例12: Strip
//' delegate void ExceptionCode();
public static MemoryStream Strip(Stream inputStream)
{
//We will try to strip the header and footer for any gzip compressed stream here
//This is needed for Deflate testing
var outputStream = new MemoryStream();
bool fText, fCRC, fextra, fname, fComment;
Byte flag;
int len;
int value;
//Header
//See RFC 1952 - ftp://swrinde.nde.swri.edu/pub/png/documents/zlib/rfc-gzip.html
// or http://madhaus.utcs.utoronto.ca/links/ftp/doc/rfc/rfc1952.txt
//skip the first 3 bytes - ID and CM
SkipBytes(inputStream, 3);
//flag
flag = (Byte)inputStream.ReadByte();
fText = ((flag & 1) != 0);
fCRC = ((flag & 2) != 0);
fextra = ((flag & 4) != 0);
fname = ((flag & 8) != 0);
fComment = ((flag & 16) != 0);
//MTIME, XFL and OS
SkipBytes(inputStream, 6);
if (fextra)
{
len = inputStream.ReadByte();
len |= (inputStream.ReadByte() << 8);
SkipBytes(inputStream, len);
}
if (fname)
{
ReadUntilZero(inputStream);
}
if (fComment)
{
ReadUntilZero(inputStream);
}
if (fCRC)
{
SkipBytes(inputStream, 2);
}
//body
//We will now write the body to the output file
List<Byte> bitlist = new List<Byte>();
while ((value = inputStream.ReadByte()) != -1)
{
bitlist.Add((Byte)value);
// outputStream.WriteByte((Byte)value);
}
// outputStream.Close();
inputStream.Dispose();
//Footer
//The correct way to find a footer would be to read the compressed blocks but we try a different approach
//All we know about it is that it is the last 8 bytes and we will read the last 8 bytes as the footer
//We can confirm this by comparing the size of the decompressed file with the size specified in the footer
//To do this, we need to decompress the file
//@TODO!! - is it worth it??
// outputStream = new MemoryStream(outputFileName, FileMode.Create, FileAccess.Write);
// inputStream = new MemoryStream(inputFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
// outputStream.Flush();
Byte[] bits = new Byte[bitlist.Count - 8];
bitlist.CopyTo(0, bits, 0, bitlist.Count - 8);
outputStream.Write(bits, 0, bits.Length);
outputStream.Position = 0;
return outputStream;
}
示例13: NetworkRun
private void NetworkRun()
{
while (!doShutdown) {
// connection necessary?
if (client == null || !client.Connected) {
try {
client = new TcpClient();
lock (thisLock) { debug.Enqueue("trying to connect to pd"); }
client.Connect(host, port);
if (stream != null)stream.Dispose();
stream = client.GetStream();
suppressErrors = false;
}
catch(Exception e)
{
Error("network error: " + e.Message);
if (stream != null)stream.Dispose();
stream = null;
client = null;
Thread.Sleep (3 * 1000);
}
}
// deliver messages
try {
lock (thisLock) {
readyToQueuePdMessage = client != null && client.Connected;
while (client.Connected && stream != null && readyToSend.Count > 0) {
string message = readyToSend.Dequeue();
// low level mgs send
byte[] ba = asciiEncoding.GetBytes(message.Trim().TrimEnd(new char[]{';'}).Trim() + ";");
stream.Write(ba, 0, ba.Length);
suppressErrors = false;
}
}
}
catch(Exception e)
{
Error("network error: " + e.Message);
if (stream != null)stream.Dispose();
stream = null;
client = null;
Thread.Sleep (3 * 1000);
}
// sleep a while
Thread.Sleep(5);
}
}
示例14: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
byte[] byteData = null;
try
{
if (context == null)
{
context = ContextUtil.getInstance(Server.MapPath("."));
encrypt = context.getOuterEncrypt();
}
if (encoder == null)
encoder = ParamEncoder.getInstance();
if (decoder == null)
decoder = ParamDecoder.getInstance();
encoder.outEncoder = context.getOuterResolve();
decoder.outDecoder = context.getOuterResolve();
Stream input = Request.InputStream;
if (input.CanRead)
{
byteData = new byte[input.Length];
input.Read(byteData, 0, (int)input.Length);
input.Close();
input.Dispose();
// 解密
if (encrypt != null)
byteData = encrypt.decrypt(byteData);
dataVo = decoder.decoder(byteData);
Type serviceCls = context.getService(context.getServiceNameSpace() + "." + dataVo.ServiceName);
MethodInfo method = serviceCls.GetMethod(dataVo.MethodName);
object result = method.Invoke(System.Activator.CreateInstance(serviceCls), dataVo.Param);
dataVo.Result = result;
dataVo.ResultStatus = "success";
byte[] resultData = encoder.encode(dataVo);
if (encrypt != null)
resultData = encrypt.encrypt(resultData);
output = Response.OutputStream;
output.Write(resultData, 0, resultData.Length);
output.Flush();
output.Close();
output.Dispose();
}
else
{
}
}
catch(Exception exc)
{
if (dataVo == null && byteData != null)
dataVo = decoder.decoder(byteData);
if (dataVo == null)
dataVo = new DataVO();
dataVo.ResultStatus = "error";
dataVo.ErrorMessage = exc.ToString();
byte[] resultData = encoder.encode(dataVo);
if (encrypt != null)
resultData = encrypt.encrypt(resultData);
output = Response.OutputStream;
output.Write(resultData, 0, resultData.Length);
output.Flush();
output.Close();
output.Dispose();
}
}
示例15: imageLoadedCallback
private void imageLoadedCallback(Stream stream, bool succeeded)
{
enableButtons();
MessageBoxManager.Show("Image Status", "Image Loaded: " + succeeded);
if (!succeeded)
{
if (stream != null) stream.Dispose();
return;
}
try
{
var data = new byte[stream.Length];
stream.Read(data, 0, data.Length);
var newImage = new Texture2D(4, 4);
newImage.LoadImage(data);
newImage.Apply();
ReignImage.sprite = Sprite.Create(newImage, new Rect(0, 0, newImage.width, newImage.height), new Vector2(.5f, .5f));
}
catch (Exception e)
{
MessageBoxManager.Show("Error", e.Message);
}
finally
{
// NOTE: Make sure you dispose of this stream !!!
if (stream != null) stream.Dispose();
}
}