System.IO.BinaryReader.Dispose()

Here are the examples of the csharp api System.IO.BinaryReader.Dispose() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

95 Examples 7

19 Source : PacketLogger.cs
with BSD 3-Clause "New" or "Revised" License
from 3gstudent

public void Dispose()
        {
            if (this.m_WriteStream != null)
            {
                this.m_WriteStream.Close();
                this.m_WriteStream.Dispose();
                this.m_WriteStream = null;
            }
            if (this.m_ReadStream != null)
            {
                this.m_ReadStream.Close();
                this.m_ReadStream.Dispose();
                this.m_ReadStream = null;
            }
        }

19 Source : CodeAnalysisSettingsBinaryReader.cs
with GNU General Public License v3.0
from Acumatica

public void Dispose()
		{
			if (!_isDisposed)
			{
				_isDisposed = true;
				_reader.Dispose();
			}
		}

19 Source : ROMManager.cs
with GNU General Public License v3.0
from aglab2

public void Dispose()
        {
            reader.Dispose();
        }

19 Source : EsmFileReader.cs
with GNU General Public License v3.0
from arycama

private void OnDestroy() => reader?.Dispose();

19 Source : ForgedReader.cs
with MIT License
from baking-bad

public void Dispose()
        {
            _reader?.Dispose();
        }

19 Source : MpqArchive.cs
with The Unlicense
from BAndysc

public void Dispose()
        {
            if (_cleanupStreamOnDispose)
            {
                if (_reader != null)
                {
                    _reader.Dispose();
                    _reader = null!;
                }
            }
        }

19 Source : TEStorageUnit.cs
with MIT License
from blushiemagic

public override void NetReceive(BinaryReader trueReader, bool lightReceive)
        {
            //If the workaround is active, then the enreplacedy isn't being sent via the NetWorkaround packet
            byte workaround = trueReader.ReadByte();

            if (EditsLoader.MessageTileEnreplacedySyncing || workaround != 1)
            {
                base.NetReceive(trueReader, lightReceive);
                return;
            }

            /* Reads the buffer off the network */
            MemoryStream buffer = new MemoryStream(65536);
            BinaryWriter bufferWriter = new BinaryWriter(buffer);

            bufferWriter.Write(trueReader.ReadBytes(trueReader.ReadUInt16()));
            buffer.Position = 0;

            /* Recreate the BinaryReader reader */
            DeflateStream decompressor = new DeflateStream(buffer, CompressionMode.Decompress, true);
            BinaryReader reader = new BinaryReader(decompressor);

            /* Original code */
            base.NetReceive(reader, lightReceive);
            if (TileEnreplacedy.ByPosition.ContainsKey(Position) && TileEnreplacedy.ByPosition[Position] is TEStorageUnit)
            {
                TEStorageUnit other = (TEStorageUnit)TileEnreplacedy.ByPosition[Position];
                items = other.items;
                hreplacedpaceInStack = other.hreplacedpaceInStack;
                hasItem = other.hasItem;
            }
            receiving = true;
            int count = reader.ReadUInt16();
            bool flag = false;
            for (int k = 0; k < count; k++)
            {
                if (UnitOperation.Receive(reader, this))
                {
                    flag = true;
                }
            }
            if (flag)
            {
                RepairMetadata();
            }
            receiving = false;
            
            /* Dispose all objects */
            reader.Dispose(); decompressor.Dispose(); bufferWriter.Dispose(); buffer.Dispose();
        }

19 Source : RsaKeyUtils.cs
with MIT License
from bunq

internal static RSA DecodePublicKey(byte[] publicKeyBytes)
        {
            var ms = new MemoryStream(publicKeyBytes);
            var binaryReader = new BinaryReader(ms);
            byte[] seqOid = {0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00};

            try
            {
                byte byteValue;
                ushort shortValue;

                shortValue = binaryReader.ReadUInt16();

                switch (shortValue)
                {
                    case 0x8130:
                        binaryReader.ReadByte();
                        break;
                    case 0x8230:
                        binaryReader.ReadInt16();
                        break;
                    default:
                        return null;
                }

                var seq = binaryReader.ReadBytes(15);

                if (!Helpers.CompareByteArrays(seq, seqOid)) return null;

                shortValue = binaryReader.ReadUInt16();

                switch (shortValue)
                {
                    case 0x8103:
                        binaryReader.ReadByte();
                        break;
                    case 0x8203:
                        binaryReader.ReadInt16();
                        break;
                    default:
                        return null;
                }

                byteValue = binaryReader.ReadByte();

                if (byteValue != 0x00) return null;

                shortValue = binaryReader.ReadUInt16();

                switch (shortValue)
                {
                    case 0x8130:
                        binaryReader.ReadByte();
                        break;
                    case 0x8230:
                        binaryReader.ReadInt16();
                        break;
                    default:
                        return null;
                }

                var rsa = RSA.Create();
                var rsaParams = new RSAParameters
                {
                    Modulus = binaryReader.ReadBytes(Helpers.DecodeIntegerSize(binaryReader))
                };
                var traits = new RsaParameterTraits(rsaParams.Modulus.Length * 8);

                rsaParams.Modulus = Helpers.AlignBytes(rsaParams.Modulus, traits.SizeMod);
                rsaParams.Exponent = Helpers.AlignBytes(binaryReader.ReadBytes(Helpers.DecodeIntegerSize(binaryReader)),
                    traits.SizeExp);

                rsa.ImportParameters(rsaParams);

                return rsa;
            }
            catch (System.Exception)
            {
                return null;
            }
            finally
            {
                binaryReader.Dispose();
            }
        }

19 Source : RsaKeyUtils.cs
with MIT License
from bunq

internal static RSA DecodePrivateKeyInfo(byte[] pkcs8)
        {
            byte[] seqOid = {0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00};
            var mem = new MemoryStream(pkcs8);
            var lenstream = (int) mem.Length;
            var binaryReader = new BinaryReader(mem);

            try
            {
                var twobytes = binaryReader.ReadUInt16();

                switch (twobytes)
                {
                    case 0x8130:
                        binaryReader.ReadByte();
                        break;
                    case 0x8230:
                        binaryReader.ReadInt16();
                        break;
                    default:
                        return null;
                }

                var bt = binaryReader.ReadByte();

                if (bt != 0x02)
                    return null;

                twobytes = binaryReader.ReadUInt16();

                if (twobytes != 0x0001)
                    return null;

                var seq = binaryReader.ReadBytes(15);

                if (!CompareByteArrays(seq, seqOid)) return null;

                bt = binaryReader.ReadByte();

                if (bt != 0x04) return null;

                bt = binaryReader.ReadByte();

                switch (bt)
                {
                    case 0x81:
                        binaryReader.ReadByte();
                        break;
                    case 0x82:
                        binaryReader.ReadUInt16();
                        break;
                }

                var rsaPrivateKeyBytes = binaryReader.ReadBytes((int) (lenstream - mem.Position));

                return DecodeRsaPrivateKey(rsaPrivateKeyBytes);
            }

            catch (System.Exception)
            {
                return null;
            }

            finally
            {
                binaryReader.Dispose();
            }
        }

19 Source : RsaKeyUtils.cs
with MIT License
from bunq

private static RSAParameters DecodeRsaPrivateKeyToRsaParameters(byte[] privateKey)
        {
            var rsaParams = new RSAParameters();
            var memoryStream = new MemoryStream(privateKey);
            var binaryReader = new BinaryReader(memoryStream);

            try
            {
                var twoBytes = binaryReader.ReadUInt16();

                switch (twoBytes)
                {
                    case 0x8130:
                        binaryReader.ReadByte();
                        break;
                    case 0x8230:
                        binaryReader.ReadInt16();
                        break;
                    default:
                        return rsaParams;
                }

                twoBytes = binaryReader.ReadUInt16();

                if (twoBytes != 0x0102)
                    return rsaParams;

                var bt = binaryReader.ReadByte();

                if (bt != 0x00)
                    return rsaParams;

                var elems = GetIntegerSize(binaryReader);
                rsaParams.Modulus = binaryReader.ReadBytes(elems);

                elems = GetIntegerSize(binaryReader);
                rsaParams.Exponent = binaryReader.ReadBytes(elems);

                elems = GetIntegerSize(binaryReader);
                rsaParams.D = binaryReader.ReadBytes(elems);

                elems = GetIntegerSize(binaryReader);
                rsaParams.P = binaryReader.ReadBytes(elems);

                elems = GetIntegerSize(binaryReader);
                rsaParams.Q = binaryReader.ReadBytes(elems);

                elems = GetIntegerSize(binaryReader);
                rsaParams.DP = binaryReader.ReadBytes(elems);

                elems = GetIntegerSize(binaryReader);
                rsaParams.DQ = binaryReader.ReadBytes(elems);

                elems = GetIntegerSize(binaryReader);
                rsaParams.InverseQ = binaryReader.ReadBytes(elems);

                return rsaParams;
            }
            catch (System.Exception)
            {
                return rsaParams;
            }
            finally
            {
                binaryReader.Dispose();
            }
        }

19 Source : SerializerFixture.cs
with MIT License
from cake-build

public void Dispose()
        {
            _stream?.Dispose();
            Writer?.Dispose();
            Reader?.Dispose();
        }

19 Source : ScriptGenerationClient.cs
with MIT License
from cake-build

public void Dispose()
        {
            _cancellationTokenSource.Cancel(false);
            _process.Dispose();
            _stream?.Dispose();
            _writer?.Dispose();
            _reader?.Dispose();
        }

19 Source : Program.cs
with Apache License 2.0
from caozhiyuan

private static byte[] GetFileBytes(string str1)
        {
            lock (Locker)
            {
                var fileStream = new FileStream(str1, FileMode.Open);
                var binaryReader = new BinaryReader(fileStream);
                byte[] numArray;
                try
                {
                    numArray = binaryReader.ReadBytes((int)fileStream.Length);
                }
                finally
                {
                    binaryReader.Dispose();
                }
                return numArray;
            }
        }

19 Source : Program.cs
with Apache License 2.0
from caozhiyuan

private static void SyncTest()
        {
            StorageNode storageNode = FastDFSClient.GetStorageNodeAsync("group1").GetAwaiter().GetResult();
            string[] files = Directory.GetFiles("testimage", "*.jpg");
            string[] strArrays = files;
            for (int i = 0; i < strArrays.Length; i++)
            {
                string str1 = strArrays[i];
                var fileStream = new FileStream(str1, FileMode.Open);
                var binaryReader = new BinaryReader(fileStream);
                byte[] numArray;
                try
                {
                    numArray = binaryReader.ReadBytes((int)fileStream.Length);
                }
                finally
                {
                    binaryReader.Dispose();
                }
                var str = FastDFSClient.UploadFileAsync(storageNode, numArray, "jpg").GetAwaiter().GetResult();
                Console.WriteLine(StorageLink + str);
                FastDFSClient.RemoveFileAsync("group1", str).GetAwaiter().GetResult(); ;
                Console.WriteLine("FastDFSClient.RemoveFile" + str);
            }
        }

19 Source : DirectoryContainer.cs
with MIT License
from csinkers

public ISerializer Read(string path, replacedetInfo info, IFileSystem disk, IJsonUtil jsonUtil)
        {
            if (info == null) throw new ArgumentNullException(nameof(info));
            if (disk == null) throw new ArgumentNullException(nameof(disk));
            var subreplacedets = new Dictionary<int, (string, string)>(); // path and name
            // Pattern vars: 0=Index 1=SubItem 2=Name 3=Palette
            var pattern = info.Get(replacedetProperty.Pattern, "{0}_{1}_{2}.dat");

            foreach (var filePath in disk.EnumerateDirectory(path, $"{info.Index}_*.*"))
            {
                var filename = Path.GetFileName(filePath);
                var (index, subreplacedet, paletteId, name) = replacedetInfo.ParseFilename(pattern, filename);

                if (paletteId.HasValue)
                    info.Set(replacedetProperty.PaletteId, paletteId);

                if (index != info.Index)
                    continue;

                subreplacedets[subreplacedet] = (filePath, name);
            }

            var ms = new MemoryStream();
            if (subreplacedets.Count > 0)
            {
                using var bw = new BinaryWriter(ms, Encoding.UTF8, true);
                using var s = new AlbionWriter(bw);
                PackedChunks.PackNamed(s, subreplacedets.Keys.Max() + 1, i => 
                    !subreplacedets.TryGetValue(i, out var pathAndName)
                        ? (Array.Empty<byte>(), null)
                        : (disk.ReadAllBytes(pathAndName.Item1), pathAndName.Item2));
            }

            ms.Position = 0;
            var br = new BinaryReader(ms);
            return new AlbionReader(br, ms.Length, () =>
            {
                br.Dispose();
                ms.Dispose();
            });
        }

19 Source : DummyContainer.cs
with MIT License
from csinkers

public ISerializer Read(string path, replacedetInfo info, IFileSystem disk, IJsonUtil jsonUtil)
        {
            var ms = new MemoryStream(new byte[] { 0 });
            var br = new BinaryReader(ms);
            return new AlbionReader(br, 1, () => { br.Dispose(); ms.Dispose(); });
        }

19 Source : JsonObjectContainer.cs
with MIT License
from csinkers

[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "The serializer will handle it")]
        public ISerializer Read(string path, replacedetInfo info, IFileSystem disk, IJsonUtil jsonUtil)
        {
            if (info == null) throw new ArgumentNullException(nameof(info));
            if (disk == null) throw new ArgumentNullException(nameof(disk));
            if (jsonUtil == null) throw new ArgumentNullException(nameof(jsonUtil));
            if (!disk.FileExists(path))
                return null;

            var dict = Load(path, disk, jsonUtil);
            if (!dict.TryGetValue(info.replacedetId, out var token))
                return null;

            var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonUtil.Serialize(token)));
            var br = new BinaryReader(ms);
            return new GenericBinaryReader(
                br,
                ms.Length,
                Encoding.UTF8.GetString,
                ApiUtil.replacedert,
                () => { br.Dispose(); ms.Dispose(); });
        }

19 Source : JsonStringContainer.cs
with MIT License
from csinkers

[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "The serializer will handle it")]
        public ISerializer Read(string path, replacedetInfo info, IFileSystem disk, IJsonUtil jsonUtil)
        {
            if (info == null) throw new ArgumentNullException(nameof(info));
            if (disk == null) throw new ArgumentNullException(nameof(disk));
            if (jsonUtil == null) throw new ArgumentNullException(nameof(jsonUtil));

            var dict = Load(path, disk, jsonUtil);
            if (!dict.TryGetValue(info.replacedetId, out var value))
                return null;

            var ms = new MemoryStream(Encoding.UTF8.GetBytes(value));
            var br = new BinaryReader(ms);
            return new GenericBinaryReader(
                br,
                ms.Length,
                Encoding.UTF8.GetString,
                ApiUtil.replacedert,
                () => { br.Dispose(); ms.Dispose(); });
        }

19 Source : AlbionReader.cs
with MIT License
from csinkers

protected override void Dispose(bool disposing)
        {
            _br.Dispose();
            base.Dispose(disposing);
        }

19 Source : FormatUtil.cs
with MIT License
from csinkers

public static ISerializer SerializeWithSerdes(Action<ISerializer> serdes)
        {
            if (serdes == null) throw new ArgumentNullException(nameof(serdes));
            var ms = new MemoryStream();
            using var bw = new BinaryWriter(ms, AlbionEncoding, true);
            using var s = new AlbionWriter(bw);
            serdes(s);
            bw.Flush();
            ms.Position = 0;

            var br = new BinaryReader(ms);
            return new AlbionReader(br, ms.Length, () =>
            {
                br.Dispose();
                ms.Dispose();
            });
        }

19 Source : Save.cs
with MIT License
from Cuyler36

public void Close(bool save)
        {
            if (save)
            {
                Flush();
            }

            _saveWriter?.Dispose();
            _saveReader?.Dispose();
            _saveFile?.Dispose();
        }

19 Source : Channel.cs
with MIT License
from CyAScott

public void Dispose()
        {
            if (Interlocked.CompareExchange(ref disposed, 1, 0) != 0)
            {
                return;
            }

            using (disposeToken)
            {
                try
                {
                    disposeToken.Cancel();
                }
                catch
                {
                    // ignored
                }
            }

            Connection.Terminate(this);
            Buffer.Dispose();

            var requests = remoteRequests.Values.ToArray();
            remoteRequests.Clear();
            foreach (var request in requests)
            {
                request.TrySetCanceled();
            }

            Reader.Dispose();
        }

19 Source : ByteBuffer.cs
with GNU General Public License v3.0
from CypherCore

public void Dispose()
        {
            if (writeStream != null)
                writeStream.Dispose();

            if (readStream != null)
                readStream.Dispose();
        }

19 Source : BLTEStream.cs
with GNU General Public License v3.0
from CypherCore

protected override void Dispose(bool disposing)
        {
            try
            {
                _stream?.Dispose();
                _reader?.Dispose();
                _memStream?.Dispose();
            }
            finally
            {
                _stream = null;
                _reader = null;
                _memStream = null;

                base.Dispose(disposing);
            }
        }

19 Source : PipeLoggerServer.cs
with MIT License
from daveaglick

public void Dispose()
        {
            _binaryReader.Dispose();
            PipeStream.Dispose();
        }

19 Source : Decrypto.cs
with MIT License
from davidxuang

public void Dispose()
        {
            _reader.Dispose();
            _buffer.Dispose();
            GC.SuppressFinalize(this);
        }

19 Source : ResourcesFile.cs
with MIT License
from deepakkumar1984

public void Dispose()
		{
			reader.Dispose();
		}

19 Source : Minst.cs
with Apache License 2.0
from dreamsfly900

public static MinstLabelArr  read_Lable(string filename)// 读入图像
{
			FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
			BinaryReader br = new BinaryReader(fs);

			int magic_number = 0;
	     	int number_of_labels = 0;
	    	int label_long = 10;

			//从文件中读取sizeof(magic_number) 个字符到 &magic_number  
			 
		 
			//从文件中读取sizeof(magic_number) 个字符到 &magic_number  
			magic_number = ReverseInt(br.ReadInt32());
			number_of_labels = ReverseInt(br.ReadInt32());

			int i, l;

			// 图像标记数组的初始化
			MinstLabelArr labarr = new MinstLabelArr();
		labarr.LabelNum=number_of_labels;
	labarr.LabelPtr=new MinstLabel[number_of_labels];

	for(i = 0; i<number_of_labels; ++i)  
	{  
		labarr.LabelPtr[i].l=10;
				labarr.LabelPtr[i].LabelData = new float[label_long];
				int temp = 0;
				temp = br.ReadByte();
				labarr.LabelPtr[i].LabelData[(int)temp]=1.0f;    
	}

			br.Dispose();
			fs.Close();
			return labarr;	
}

19 Source : Minst.cs
with Apache License 2.0
from dreamsfly900

public static MinstImgArr read_Img(string filename) // 读入图像
		{

			FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
			BinaryReader br = new BinaryReader(fs);
			//cha = br.ReadChar();
			//num = br.ReadInt32();
			//doub = br.ReadDouble();
			//str = br.ReadString();
			int magic_number = 0;
			int number_of_images = 0;
			int n_rows = 0;
			int n_cols = 0;
			//从文件中读取sizeof(magic_number) 个字符到 &magic_number  
			magic_number = ReverseInt(br.ReadInt32());
			number_of_images = ReverseInt( br.ReadInt32());
			n_rows = ReverseInt(br.ReadInt32());
			n_cols = ReverseInt(br.ReadInt32());


			int i, r, c;

			// 图像数组的初始化
			MinstImgArr imgarr = new MinstImgArr();
			imgarr.ImgNum = number_of_images;
			imgarr.ImgPtr = new MinstImg[number_of_images];

			for (i = 0; i < number_of_images; ++i)
			{
				imgarr.ImgPtr[i].r = n_rows;
				imgarr.ImgPtr[i].c = n_cols;
				imgarr.ImgPtr[i].ImgData = new float[n_rows, n_cols];
				for (r = 0; r < n_rows; ++r)
				{
					 
					for (c = 0; c < n_cols; ++c)
					{
						 int temp = 0;
						 temp=br.ReadByte();
						imgarr.ImgPtr[i].ImgData[r,c] = (float)temp / 255.0f;
					}
				}
			}
			br.Dispose();
			fs.Close();
			return imgarr;
		}

19 Source : ByteHelper.cs
with MIT License
from egonl

public void Dispose()
        {
            if (_binaryReader != null)
            {
                _binaryReader.Dispose();
            }
        }

19 Source : BsonReader.cs
with Apache License 2.0
from elastic

public override void Close()
		{
			base.Close();

			if (CloseInput)
			{
#if HAVE_STREAM_READER_WRITER_CLOSE
                _reader?.Close();
#else
				_reader?.Dispose();
#endif
			}
		}

19 Source : Shared.cs
with GNU General Public License v2.0
from emoose

public void Dispose()
        {
            Stream.Dispose();
            Reader.Dispose();
            Writer.Dispose();
        }

19 Source : LoggerDescription_Tests.cs
with MIT License
from enricosada

[Fact]
        public void LoggerDescriptionCustomSerialization()
        {
            string clreplacedName = "Clreplaced";
            string loggerreplacedemblyName = "Clreplaced";
            string loggerFilereplacedembly = null;
            string loggerSwitchParameters = "Clreplaced";
            LoggerVerbosity verbosity = LoggerVerbosity.Detailed;

            LoggerDescription description = new LoggerDescription(clreplacedName, loggerreplacedemblyName, loggerFilereplacedembly, loggerSwitchParameters, verbosity);
            MemoryStream stream = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(stream);
            BinaryReader reader = new BinaryReader(stream);
            try
            {
                stream.Position = 0;
                description.WriteToStream(writer);
                long streamWriteEndPosition = stream.Position;
                stream.Position = 0;
                LoggerDescription description2 = new LoggerDescription();
                description2.CreateFromStream(reader);
                long streamReadEndPosition = stream.Position;
                replacedert.Equal(streamWriteEndPosition, streamReadEndPosition); // "Stream end positions should be equal"

                replacedert.Equal(description.Verbosity, description2.Verbosity); // "Expected Verbosity to Match"
                replacedert.Equal(description.LoggerId, description2.LoggerId); // "Expected Verbosity to Match"
                replacedert.Equal(0, string.Compare(description.LoggerSwitchParameters, description2.LoggerSwitchParameters, StringComparison.OrdinalIgnoreCase)); // "Expected LoggerSwitchParameters to Match"
                replacedert.Equal(0, string.Compare(description.Name, description2.Name, StringComparison.OrdinalIgnoreCase)); // "Expected Name to Match"
            }
            finally
            {
                reader.Dispose();
                writer = null;
                stream = null;
            }
        }

19 Source : GhostNetRemoteConnection.cs
with MIT License
from EverestAPI

protected override void Dispose(bool disposing) {
            lock (DisposeLock) {
                if (Disposed)
                    return;
                Disposed = true;

                base.Dispose(disposing);

                ManagementReader?.Dispose();
                ManagementReader = null;

                ManagementStream?.Dispose();
                ManagementStream = null;

                ManagementClient?.Close();
                ManagementClient = null;

                UpdateClient?.Close();
                UpdateClient = null;
            }
        }

19 Source : ZipArchive.cs
with MIT License
from FenPhoenix

private void Dispose(bool disposing)
        {
            if (disposing && !_isDisposed)
            {
                ArchiveStream.Dispose();
                _backingStream?.Dispose();
                ArchiveReader?.Dispose();

                _isDisposed = true;
            }
        }

19 Source : SampleReader.cs
with Apache License 2.0
from geeooff

protected virtual void Dispose(bool isDisposing)
		{
			if (!_isDisposed)
			{
				if (isDisposing)
				{
					_reader.Dispose();
				}

				_isDisposed = true;
			}
		}

19 Source : RatClient.cs
with MIT License
from gigajew

public void Dispose()
        {
            Input?.Dispose();
            Output?.Dispose();
            Stream?.Dispose();
            socket?.Dispose();
        }

19 Source : XPostprocessClip.cs
with MIT License
from huailiang

public void ReadFromBuffer()
        {
            if (data.buffer != null)
            {
                using (MemoryStream stream = new MemoryStream(data.buffer))
                {
                    BinaryReader reader = new BinaryReader(stream);
                    ReadCurves(reader);
                    reader.Dispose();
                }
            }
        }

19 Source : DurableQueue.cs
with Apache License 2.0
from IPCConnectedFactoryExchange

public void Close()
        {
            if (dataWriter != null) dataWriter.Dispose();
            if (dataReader != null) dataReader.Dispose();
            dataWriter = null;
            dataReader = null;
        }

19 Source : XEFEventStreamReader.cs
with MIT License
from Isaac-W

protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    // Dispose managed resources
                    _reader.Dispose();
                }

                disposed = true;
            }
        }

19 Source : PciReader.cs
with MIT License
from ixy-languages

public void Dispose()
        {
            _binReader?.Dispose();
            _binReader = null;
        }

19 Source : BsonDataReader.cs
with MIT License
from JamesNK

public override void Close()
        {
            base.Close();

            if (CloseInput)
            {
#if HAVE_STREAM_READER_WRITER_CLOSE
                _reader?.Close();
#else
                _reader?.Dispose();
#endif
            }
        }

19 Source : Reproductor_Sonidos.cs
with GNU General Public License v3.0
from Jupisoft111

internal static SoundPlayer Cargar_Sonido(string Nombre, double Porcentaje_Frecuencia, double Porcentaje_Volumen, double Ángulo_Estéreo)
        {
            try
            {
                if (!string.IsNullOrEmpty(Ruta_Sonidos) && Directory.Exists(Ruta_Sonidos) && !string.IsNullOrEmpty(Nombre))
                {
                    string Ruta = Ruta_Sonidos + "\\" + Nombre + ".wav";
                    if (File.Exists(Ruta))
                    {
                        FileStream Lector = new FileStream(Ruta, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
                        if (Lector.Length > 44L) // At least has a RIFF WAVE header
                        {
                            double Porcentaje_L = 100d; // Default volume at 100 %.
                            double Porcentaje_R = 100d;
                            Ángulo_Estéreo = (((360d - Ángulo_Estéreo) - 180d) * 100d) / 180d; // Invert the angle, make it in the range of -180 to +180 and finally convert it to a percentage between -100 and +100.
                            if (Ángulo_Estéreo != 0d) // Hopefully this simple stereo trick will work.
                            {
                                //if (Ángulo_Estéreo < 0d) Porcentaje_R -= 100d - Math.Abs(Ángulo_Estéreo);
                                //else Porcentaje_L -= 100d - Ángulo_Estéreo;
                                if (Ángulo_Estéreo < 0d) Porcentaje_R = (Porcentaje_R - (100d - Math.Abs(Ángulo_Estéreo))) / 2d;
                                else Porcentaje_L = (Porcentaje_L - (100d - Ángulo_Estéreo)) / 2d;
                            }
                            bool Modificar = Porcentaje_Volumen < 100d || Porcentaje_L < 100d || Porcentaje_R < 100d;
                            //Ángulo_Estéreo -= 180d;
                            //if (Ángulo_Estéreo < 0d) Ángulo_Estéreo = 180d - (Ángulo_Estéreo + 360d);
                            Lector.Seek(0L, SeekOrigin.Begin);
                            // Warning: this code replacedumes the WAV file is 16 bits stereo at 44100 Hz.
                            BinaryReader Lector_Binario = new BinaryReader(Lector, Encoding.ASCII);
                            if (new string(Lector_Binario.ReadChars(4)) != "RIFF") throw new Exception("Invalid file format 1");
                            Lector_Binario.ReadInt32(); // File length minus first 8 bytes of RIFF description, we don't use it
                            if (new string(Lector_Binario.ReadChars(4)) != "WAVE") throw new Exception("Invalid file format 2");
                            if (new string(Lector_Binario.ReadChars(4)) != "fmt ") throw new Exception("Invalid file format 3");
                            int Longitud_Formato = Lector_Binario.ReadInt32();
                            if (Longitud_Formato < 16) throw new Exception("Invalid file format 4"); // bad format chunk length
                                                                                                     //Lector_WAV.Seek(Lector_WAV.Position + Longitud_Formato, SeekOrigin.Begin);
                                                                                                     //Byte[] Matriz_Bytes_Formato = new Byte[Longitud_Formato];
                                                                                                     //Lector.Read(Matriz_Bytes_Formato, 0, Matriz_Bytes_Formato.Length);
                                                                                                     //Matriz_Bytes_Formato = null;
                            Lector_Binario.ReadInt16(); // wFormatTag
                            Lector_Binario.ReadInt16(); // nChannels
                            long Reproductor_Índice_Frecuencia = Lector.Position;
                            int Frecuencia_Original = Lector_Binario.ReadInt32(); // nSamplesPerSec
                            long Reproductor_Índice_Bytes_Segundo = Lector.Position;
                            int Abc = Lector_Binario.ReadInt32(); // nAvgBytesPerSec
                            Lector_Binario.ReadInt16(); // nBlockAlign
                            Lector_Binario.ReadInt16(); // wBitsPerSample
                                                        //Lector_Binario.Read(null, 0, 128);
                                                        //Lector_Binario.ReadInt64();
                                                        //Lector_Binario.ReadInt64();
                                                        // advance in the stream to skip the wave format block 
                            Longitud_Formato -= 16; // minimum format size

                            //MessageBox.Show(Reproductor_Índice_Frecuencia.ToString(), Reproductor_Índice_Bytes_Segundo.ToString());
                            //MessageBox.Show(Frecuencia_Original.ToString(), Abc.ToString());

                            while (Longitud_Formato > 0)
                            {
                                Lector_Binario.ReadByte();
                                Longitud_Formato--;
                            }
                            //MessageBox.Show(Lector.Position.ToString());
                            // replacedume the data chunk is aligned
                            //Lector.Seek(36L, SeekOrigin.Begin);
                            //MessageBox.Show(Lector.Position.ToString());
                            int Byte_Anterior_1 = Lector.ReadByte();
                            int Byte_Anterior_2 = Lector.ReadByte();
                            int Byte_Anterior_3 = Lector.ReadByte();
                            while (Lector.Position < Lector.Length)
                            {
                                int Byte_Actual = Lector.ReadByte();
                                if (Byte_Anterior_1 == 100 && Byte_Anterior_2 == 97 && Byte_Anterior_3 == 116 && Byte_Actual == 97) break; // data
                                else
                                {
                                    Byte_Anterior_1 = Byte_Anterior_2;
                                    Byte_Anterior_2 = Byte_Anterior_3;
                                    Byte_Anterior_3 = Byte_Actual;
                                }
                            }
                            if (Lector.Position >= Lector.Length) throw new Exception("Invalid file format 5");

                            long Reproductor_Longitud_Samples = Lector_Binario.ReadUInt32();
                            long Reproductor_Índice_Samples = Lector.Position;

                            List<byte> Lista_Bytes = new List<byte>(); // Buffer for the modified sound.
                            byte[] Matriz_Bytes_Cabecera = new byte[Reproductor_Índice_Samples];
                            Lector.Seek(0L, SeekOrigin.Begin);
                            Lector.Read(Matriz_Bytes_Cabecera, 0, Matriz_Bytes_Cabecera.Length);
                            // Modify the frequency of the sound (pitch):
                            //if (Frecuencia >= 100 && Frecuencia <= 200000)
                            if (Porcentaje_Frecuencia != 100d)
                            {
                                int Frecuencia = (int)Math.Round(((double)Frecuencia_Original * Porcentaje_Frecuencia) / 100d, MidpointRounding.AwayFromZero);
                                if (Frecuencia < 100) Frecuencia = 100;
                                else if (Frecuencia > 200000) Frecuencia = 200000;
                                byte[] Matriz_Bytes_Frecuencia = BitConverter.GetBytes(Frecuencia);
                                //Array.Reverse(Matriz_Bytes_Frecuencia);
                                Matriz_Bytes_Frecuencia.CopyTo(Matriz_Bytes_Cabecera, Reproductor_Índice_Frecuencia);
                                Matriz_Bytes_Frecuencia = null;
                            }
                            Lista_Bytes.AddRange(Matriz_Bytes_Cabecera);

                            // Modifiy the volume of the channels to simulate the selected stereo angle (so for example the sound will seem to come from the same place where a lightning strikes on the screen).
                            byte[] Matriz_Bytes = new byte[4096];
                            for (long Índice_Bloque = 0L; Índice_Bloque <= Reproductor_Longitud_Samples; Índice_Bloque += 4096L)
                            {
                                Lector.Seek(Reproductor_Índice_Samples + Índice_Bloque, SeekOrigin.Begin);
                                int Longitud = Lector.Read(Matriz_Bytes, 0, Matriz_Bytes.Length);
                                if (Modificar) // Avoid modifying the sound if nothing in it should change.
                                {
                                    for (int Índice_L = 0, Índice_R = 2; Índice_L < Longitud; Índice_L += 4, Índice_R += 4) // Add 4 bytes to skip a left and right 16 bits sample pair.
                                    {
                                        //long Sample_L = (long)BitConverter.ToInt16(Matriz_Bytes, Índice_L); // Convert the 2 left channel bytes to a 16 bits sound sample between -32768 and +32767.
                                        //long Sample_R = (long)BitConverter.ToInt16(Matriz_Bytes, Índice_R);
                                        if (Porcentaje_L < 100d)
                                        {
                                            int Sample_L = (int)Math.Round((((double)BitConverter.ToInt16(Matriz_Bytes, Índice_L) * Porcentaje_Volumen) * Porcentaje_L) / 10000d, MidpointRounding.AwayFromZero); // Load and convert the sample to the specified percentage.
                                            if (Sample_L < -32768) Sample_L = -32768; // Check for out of boundaries values.
                                            else if (Sample_L > 32767) Sample_L = 32767;
                                            BitConverter.GetBytes((short)Sample_L).CopyTo(Matriz_Bytes, Índice_L); // Return the sample with the modified volume to the byte array.
                                        }
                                        if (Porcentaje_R < 100d)
                                        {
                                            int Sample_R = (int)Math.Round((((double)BitConverter.ToInt16(Matriz_Bytes, Índice_R) * Porcentaje_Volumen) * Porcentaje_R) / 10000d, MidpointRounding.AwayFromZero);
                                            if (Sample_R < -32768) Sample_R = -32768;
                                            else if (Sample_R > 32767) Sample_R = 32767;
                                            BitConverter.GetBytes((short)Sample_R).CopyTo(Matriz_Bytes, Índice_R);
                                        }
                                        //long Sample_L_0_65535 = Sample_L + 32768L; // Add +32768 to the sample to avoid working with negative numbers.
                                        //long Sample_R_0_65535 = Sample_R + 32768L;
                                        //long Volumen_L = Math.Abs(Sample_L < 0 ? Sample_L + 1L : Sample_L); // Convert the signed sample to volume.
                                        //long Volumen_R = Math.Abs(Sample_R < 0 ? Sample_R + 1L : Sample_R);
                                    }
                                }
                                Lista_Bytes.AddRange(Matriz_Bytes); // Write the modified samples to the bytes buffer.
                                                                    //Lector.Seek(Reproductor_Índice_Samples + Índice_Bloque, SeekOrigin.Begin);
                                                                    //Lector.Write(Matriz_Bytes, 0, Matriz_Bytes.Length);
                            }
                            Lector_Binario.Close();
                            Lector_Binario.Dispose();
                            Lector_Binario = null;
                            Lector.Close();
                            Lector.Dispose();
                            Lector = null;
                            //File.WriteAllBytes(Application.StartupPath + "\\jhgfd.wav", Lector_Memoria.ToArray());
                            //SoundPlayer Reproductor = new SoundPlayer(new FileStream(Application.StartupPath + "\\jhgfd.wav", FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
                            SoundPlayer Reproductor = new SoundPlayer(new MemoryStream(Lista_Bytes.ToArray()));
                            Reproductor.Load();
                            Lista_Bytes = null;
                            return Reproductor;
                        }
                        Lector.Close();
                        Lector.Dispose();
                        Lector = null;
                    }
                }
            }
            catch (Exception Excepción) { Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); }
            return null;
        }

19 Source : Ventana_Depurador_Excepciones.cs
with GNU General Public License v3.0
from Jupisoft111

private void Ventana_Depurador_Excepciones_FormClosing(object sender, FormClosingEventArgs e)
        {
            Lector_Depurador_Binario.Close();
            Lector_Depurador_Binario.Dispose();
            Lector_Depurador_Binario = null;
            Lector_Depurador.Close();
            Lector_Depurador.Dispose();
            Lector_Depurador = null;
        }

19 Source : XNA_Jupisoft.cs
with GNU General Public License v3.0
from Jupisoft111

internal static bool Convertir_XNB_a_WAV(string Ruta_Entrada, string Ruta_Salida)
        {
            //Microsoft.Xna.Framework.Content.ContentManager cm = new Microsoft.Xna.Framework.Content.ContentManager(IServiceProvider

            ushort wFormatTag;
            ushort nChannels;
            uint nSamplesPerSec;
            uint nAvgBytesPerSec;
            ushort nBlockAlign;
            ushort wBitsPerSample;
            int dataChunkSize;
            byte[] waveData;

            FileStream Lector_Entrada = new FileStream(Ruta_Entrada, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);

            int q;
            XNA_Jupisoft.PrepareStream(Lector_Entrada, null, out q);
            return false;

            BinaryReader Lector_Entrada_Binario = new BinaryReader(Lector_Entrada, Encoding.ASCII);
            string format = new string(Lector_Entrada_Binario.ReadChars(3));
            if (format != "XNB") return false; // "Invalid file format: " + format;
            char platform = Lector_Entrada_Binario.ReadChar();
            if (platform != 'w') return false; // "Invalid platform: " + platform;
            int xnaVersion = Lector_Entrada_Binario.ReadByte();
            if (xnaVersion != 5)
            {
                MessageBox.Show("Unimplemented XNA version: " + xnaVersion);
                return false; // "Unimplemented XNA version: " + xnaVersion;
            }
            byte profile = Lector_Entrada_Binario.ReadByte();
            if (profile != 0)
            {
                MessageBox.Show("Unimplemented profile: " + profile);
                //return false;
            }
            uint fileLength = Lector_Entrada_Binario.ReadUInt32();
            if (fileLength != Lector_Entrada.Length)
            {
                MessageBox.Show("File length mismatch: " + fileLength + " - should be " + Lector_Entrada.Length);
                //return false;
            }
            uint typeCount = (uint)Read7BitEncodedInt(Lector_Entrada_Binario);
            if (typeCount != 1)
            {
                MessageBox.Show("Too many types: " + typeCount);
                //return false;
            }
            // Should be in a for loop but I'm too lazy to add support for multiple types.
            string type = Lector_Entrada_Binario.ReadString();
            if (type != "Microsoft.Xna.Framework.Content.SoundEffectReader")
            {
                MessageBox.Show("Wrong type reader name: " + type);
                //return false;
            }
            int typeReaderVersion = Lector_Entrada_Binario.ReadInt32();
            if (typeReaderVersion != 0)
            {
                MessageBox.Show("Wrong type reader version: " + typeReaderVersion);
                //return false;
            }
            uint sharedResourcesCount = (uint)Read7BitEncodedInt(Lector_Entrada_Binario);
            if (sharedResourcesCount != 0)
            {
                MessageBox.Show("Too many shared resources: " + sharedResourcesCount);
                //return false;
            }
            if (Read7BitEncodedInt(Lector_Entrada_Binario) != 1)
            {
                MessageBox.Show("???");
                //return false;
            }
            // WAVE format
            uint formatChunkSize = Lector_Entrada_Binario.ReadUInt32();
            if (formatChunkSize != 18)
            {
                MessageBox.Show("Wrong format chunk size: " + formatChunkSize);
                //return false;
            }
            if ((wFormatTag = Lector_Entrada_Binario.ReadUInt16()) != 1)
            {
                MessageBox.Show("Unimplemented wav codec (must be PCM)");
                //return false;
            }
            nChannels = Lector_Entrada_Binario.ReadUInt16();
            nSamplesPerSec = Lector_Entrada_Binario.ReadUInt32();
            nAvgBytesPerSec = Lector_Entrada_Binario.ReadUInt32();
            nBlockAlign = Lector_Entrada_Binario.ReadUInt16();
            wBitsPerSample = Lector_Entrada_Binario.ReadUInt16();
            if (nAvgBytesPerSec != (nSamplesPerSec * nChannels * (wBitsPerSample / 8)))
            {
                MessageBox.Show("Average bytes per second number incorrect");
                return false;
            }
            if (nBlockAlign != (nChannels * (wBitsPerSample / 8)))
            {
                MessageBox.Show("Block align number incorrect");
                return false;
            }
            Lector_Entrada_Binario.ReadUInt16();
            waveData = Lector_Entrada_Binario.ReadBytes(dataChunkSize = Lector_Entrada_Binario.ReadInt32());

            MessageBox.Show("Done!");
            return false;

            Stream Lector_Salida = File.Create(Ruta_Salida);
            BinaryWriter Lector_Salida_Binario = new BinaryWriter(Lector_Salida);
            Lector_Salida_Binario.Write("RIFF".ToCharArray());
            Lector_Salida_Binario.Write(dataChunkSize + 36);
            Lector_Salida_Binario.Write("WAVE".ToCharArray());
            Lector_Salida_Binario.Write("fmt ".ToCharArray());
            Lector_Salida_Binario.Write(16);
            Lector_Salida_Binario.Write(wFormatTag);
            Lector_Salida_Binario.Write(nChannels);
            Lector_Salida_Binario.Write(nSamplesPerSec);
            Lector_Salida_Binario.Write(nAvgBytesPerSec);
            Lector_Salida_Binario.Write(nBlockAlign);
            Lector_Salida_Binario.Write(wBitsPerSample);
            Lector_Salida_Binario.Write("data".ToCharArray());
            Lector_Salida_Binario.Write(dataChunkSize);
            Lector_Salida_Binario.Write(waveData);

            Lector_Salida_Binario.Close();
            Lector_Salida_Binario.Dispose();
            Lector_Salida_Binario = null;
            Lector_Salida.Close();
            Lector_Salida.Dispose();
            Lector_Salida = null;
            Lector_Entrada_Binario.Close();
            Lector_Entrada_Binario.Dispose();
            Lector_Entrada_Binario = null;
            Lector_Entrada.Close();
            Lector_Entrada.Dispose();
            Lector_Entrada = null;
            return true; // "Successfully converted " + Path.GetFileNameWithoutExtension(Ruta_Entrada);
        }

19 Source : ZPayRsaHelper.cs
with Apache License 2.0
from KevinWG

private static RSA DecodeRSAPrivateKey(byte[] privkey)
        {
            var mem = new MemoryStream(privkey);
            var binr = new BinaryReader(mem);  
            try
            {
                var twobytes = binr.ReadUInt16();
                switch (twobytes)
                {
                    case 0x8130:
                        binr.ReadByte();    //advance 1 byte
                        break;
                    case 0x8230:
                        binr.ReadInt16();    //advance 2 bytes
                        break;
                    default:
                        return null;
                }

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102) //version number
                    return null;

                var bt = binr.ReadByte();
                if (bt != 0x00)
                    return null;

                var rsaParams = new RSAParameters();

                var elems = GetIntegerSize(binr);
                rsaParams.Modulus = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                rsaParams.Exponent = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                rsaParams.D = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                rsaParams.P = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                rsaParams.Q = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                rsaParams.DP = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                rsaParams.DQ = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                rsaParams.InverseQ = binr.ReadBytes(elems);

                var rsa = RSA.Create();
                rsa.ImportParameters(rsaParams);

                return rsa;
            }
            finally
            {
                binr.Dispose();
                mem.Dispose();
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from kunzmi

private static float[] ReadRAWFloat(string filename)
        {
            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
            BinaryReader bw = new BinaryReader(fs);
            int dimX = bw.ReadInt32();
            int dimY = bw.ReadInt32();
            int c = bw.ReadInt32();
            if (c != 1)
                throw new FileLoadException("This is not a one channel image!");

            float[] data = new float[dimX * dimY];

            unsafe
            {
                fixed (float* ptr = data)
                {
                    byte[] buffer = bw.ReadBytes(dimX * dimY * sizeof(float));
                    Marshal.Copy(buffer, 0, (IntPtr)ptr, dimX * dimY * sizeof(float));
                }
            }
            fs.Close();
            bw.Dispose();
            fs.Dispose();
            return data;
        }

19 Source : Program.cs
with GNU General Public License v3.0
from kunzmi

private static float3[] ReadRAWFloat3(string filename)
        {
            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
            BinaryReader bw = new BinaryReader(fs);
            int dimX = bw.ReadInt32();
            int dimY = bw.ReadInt32();
            int c = bw.ReadInt32();
            if (c != 3)
                throw new FileLoadException("This is not a three channel image!");

            float3[] data = new float3[dimX * dimY];

            unsafe
            {
                fixed (float3* ptr = data)
                {
                    byte[] buffer = bw.ReadBytes(dimX * dimY * (int)float3.SizeOf);
                    Marshal.Copy(buffer, 0, (IntPtr)ptr, dimX * dimY * (int)float3.SizeOf);
                }
            }
            fs.Close();
            bw.Dispose();
            fs.Dispose();
            return data;
        }

19 Source : ShiftCollection.cs
with GNU General Public License v3.0
from kunzmi

public void restoreOptimisedShifts(string filename)
        {
            float2[] dump = shiftsOneToOne_d;

            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);

            for (int i = 0; i < dump.Length; i++)
            {
                dump[i].x = br.ReadSingle();
                dump[i].y = br.ReadSingle();
            }
            shiftsOneToOne_d.CopyToDevice(dump);

            br.Close();
            br.Dispose();
            fs.Close();
            fs.Dispose();

        }

19 Source : SARC.cs
with GNU General Public License v3.0
from kwsch

public void Dispose()
        {
            stream.Dispose();
            br.Dispose();
        }

See More Examples