System.IO.MemoryStream.Seek(long, System.IO.SeekOrigin)

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

2026 Examples 7

19 View Source File : IOHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string XMLSerializer(object args)
        {
            if (args == null)
            {
                return null;
            }
            using (var ms = new MemoryStream())
            {
                var ds = new DataContractSerializer(args.GetType());
                ds.WriteObject(ms, args);
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);
                var sr = new StreamReader(ms);
                return sr.ReadToEnd();
            }
        }

19 View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

public static unsafe BitmapSource DdsToPng(MemoryStream buffer) {
            Pfim.IImage image;
            var tag = stackalloc byte[4];
            buffer.Read(new Span<byte>(tag, 4));
            bool dispose;
            if (dispose = * (int*)tag != 0x20534444) // "DDS "
                buffer = new MemoryStream(BrotliSharpLib.Brotli.DecompressBuffer(buffer.ToArray(), 4, (int)buffer.Length - 4));
            buffer.Seek(0, SeekOrigin.Begin);
            image = Pfim.Pfim.FromStream(buffer);
            image.Decompress();
            if (dispose)
                buffer.Close();
            return BitmapSource.Create(image.Width, image.Height, 96.0, 96.0,
            PixelFormat(image), null, image.Data, image.Stride);
        }

19 View Source File : MessageBuffer.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public ClientMessage GetMessage()
        {
            fragments.Sort(delegate (ClientPacketFragment x, ClientPacketFragment y) { return x.Header.Index - y.Header.Index; });
            MemoryStream stream = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(stream);
            foreach (ClientPacketFragment fragment in fragments)
            {
                writer.Write(fragment.Data);
            }
            stream.Seek(0, SeekOrigin.Begin);
            return new ClientMessage(stream);
        }

19 View Source File : MemoryIterator.cs
License : Apache License 2.0
Project Creator : aequabit

public bool ReadString(long offset, SeekOrigin origin, out string lpBuffer, int len = -1, Encoding stringEncoding = null)
        {
            lpBuffer = null;
            byte[] buffer = new byte[(len > 0) ? len : 0x40];
            if (stringEncoding == null)
            {
                stringEncoding = Encoding.ASCII;
            }
            try
            {
                this._base.Seek(offset, origin);
                StringBuilder builder = new StringBuilder((len > 0) ? len : 260);
                int length = -1;
                int num2 = 0;
                int startIndex = 0;
                while ((length == -1) && ((num2 = this._base.Read(buffer, 0, buffer.Length)) > 0))
                {
                    builder.Append(stringEncoding.GetString(buffer));
                    length = builder.ToString().IndexOf('\0', startIndex);
                    startIndex += num2;
                    if ((len > 0) && (startIndex >= len))
                    {
                        break;
                    }
                }
                if (length > -1)
                {
                    lpBuffer = builder.ToString().Substring(0, length);
                }
                else if ((startIndex >= len) && (len > 0))
                {
                    lpBuffer = builder.ToString().Substring(0, len);
                }
                return (lpBuffer != null);
            }
            catch (Exception exception)
            {
                return this.SetLastError(exception);
            }
        }

19 View Source File : MemoryFileProvider.cs
License : MIT License
Project Creator : adams85

public void WriteContent(string path, string content, Encoding encoding = null, bool append = false)
        {
            path = NormalizePath(path);

            CancellationTokenSource changeTokenSource = null;
            lock (_catalog)
                using (MemoryStream stream = GetStreamCore(path, out File file))
                {
                    if (content.Length == 0)
                        return;

                    if (!append)
                        stream.SetLength(0);
                    else
                        stream.Seek(0, SeekOrigin.End);

                    var writer = new StreamWriter(stream, encoding ?? Encoding.UTF8);
                    writer.Write(content);
                    writer.Flush();

                    if (file.ChangeTokenSource != null)
                    {
                        changeTokenSource = file.ChangeTokenSource;
                        file.ChangeTokenSource = new CancellationTokenSource();
                    }
                }

            changeTokenSource?.Cancel();
        }

19 View Source File : GZip.cs
License : Apache License 2.0
Project Creator : AantCoder

public static byte[] Serialize(object obj)
        {
            using (var msi = new MemoryStream())
            {
                if (formatter == null) formatter = new BinaryFormatter();
                formatter.Serialize(msi, obj);
                msi.Seek(0, SeekOrigin.Begin);
                return msi.ToArray();
            }
        }

19 View Source File : ResourceFile.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public void Write(Stream data)
        {
            var bw = new BinaryWriter(data);
            
            if (SystemMemSize != _systemMemData.Length || GraphicsMemSize != _graphicsMemData.Length)
            {
                _header.SetMemSizes(SystemMemSize, GraphicsMemSize);
            }

            _header.Write( bw );

            var ms = new MemoryStream();
            ms.Write(_systemMemData, 0, _systemMemData.Length);
            ms.Write(new byte[SystemMemSize - _systemMemData.Length], 0, SystemMemSize - _systemMemData.Length);
            ms.Write(_graphicsMemData, 0, _graphicsMemData.Length);
            ms.Write(new byte[GraphicsMemSize - _graphicsMemData.Length], 0, GraphicsMemSize - _graphicsMemData.Length);

            ms.Seek(0, SeekOrigin.Begin);

            var msCompress = new MemoryStream();

            _codec.Compress( ms, msCompress );

            bw.Write(msCompress.ToArray());

            ms.Close();
            msCompress.Close();

            bw.Flush();
        }

19 View Source File : StreamSerializeTest.cs
License : MIT License
Project Creator : 1996v

[Fact]
        public void MemoryStreamSerializeAndDeserialize_MultipleValues_ConsecutiveReadsAndWrites_IsCorrect()
        {
            var obj1 = new List<int>() { 1 };
            var obj2 = new Dictionary<string, object>() { { "A", DateTime.MinValue } };
            var obj3 = double.MaxValue;

            MemoryStream stream = new MemoryStream();
            BssomSerializer.Serialize(stream, obj1);
            BssomSerializer.Serialize(stream, obj2);
            BssomSerializer.Serialize(stream, obj3);

            stream.Seek(0, SeekOrigin.Begin);

            var oobj1 = BssomSerializer.Deserialize<List<int>>(stream);
            var oobj2 = BssomSerializer.Deserialize<Dictionary<string, object>>(stream);
            var oobj3 = BssomSerializer.Deserialize<double>(stream);

            oobj1.Count.Is(obj1.Count);
            oobj1[0].Is(oobj1[0]);
            oobj2.Count.Is(obj2.Count);
            oobj2["A"].Is(oobj2["A"]);
            oobj3.Is(obj3);
        }

19 View Source File : WebSocketExtends.cs
License : MIT License
Project Creator : AiursoftWeb

public static async Task Subscribe(this WebSocket ws, Func<string, Task> onNewMessage)
        {
            var ms = new MemoryStream();
            while (ws.State == WebSocketState.Open)
            {
                WebSocketReceiveResult result;
                do
                {
                    var messageBuffer = WebSocket.CreateClientBuffer(1024, 16);
                    result = await ws.ReceiveAsync(messageBuffer, CancellationToken.None);
                    ms.Write(messageBuffer.Array ?? Array.Empty<byte>(), messageBuffer.Offset, result.Count);
                }
                while (!result.EndOfMessage);

                if (result.MessageType == WebSocketMessageType.Text)
                {
                    var msgString = Encoding.UTF8.GetString(ms.ToArray());
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.SetLength(0);
                    await onNewMessage(msgString);
                }
                else
                {
                    throw new InvalidOperationException();
                }
            }
        }

19 View Source File : RdpPacket.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent

public void InsertByte(byte value)
        {
            long position = this.Position;
            this.Seek(0L, SeekOrigin.End);
            this.WriteByte(0);
            byte[] sourceArray = this.GetBuffer();
            Array.Copy(sourceArray, (int) position, sourceArray, ((int) position) + 1, (int) ((sourceArray.Length - position) - 1L));
            this.Position = position;
            this.WriteByte(value);
        }

19 View Source File : MemoryIterator.cs
License : Apache License 2.0
Project Creator : aequabit

public bool Read(long offset, SeekOrigin origin, byte[] buffer)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer", "Parameter cannot be null");
            }
            try
            {
                this._base.Seek(offset, origin);
                this._base.Read(buffer, 0, buffer.Length);
            }
            catch (Exception exception)
            {
                this.SetLastError(exception);
                buffer = null;
            }
            return (buffer != null);
        }

19 View Source File : MemoryFileProvider.cs
License : MIT License
Project Creator : adams85

private MemoryStream GetStreamCore(string path, out File file)
        {
            if (!_catalog.TryGetValue(path, out file) || file.IsDirectory)
                throw new InvalidOperationException("File does not exist.");

            if (file.IsOpen)
                throw new InvalidOperationException("File is in use currently.");

            file.IsOpen = true;

            file.Content.Seek(0, SeekOrigin.Begin);
            return file.Content;
        }

19 View Source File : SevenZipHelper.cs
License : MIT License
Project Creator : 91Act

public static MemoryStream StreamDecompress(MemoryStream newInStream, long outSize)
        {
            Decoder decoder = new Decoder();

            newInStream.Seek(0, 0);
            MemoryStream newOutStream = new MemoryStream();

            byte[] properties2 = new byte[5];
            if (newInStream.Read(properties2, 0, 5) != 5)
                throw (new Exception("input .lzma is too short"));
            decoder.SetDecoderProperties(properties2);

            long compressedSize = newInStream.Length - newInStream.Position;
            decoder.Code(newInStream, newOutStream, compressedSize, outSize, null);

            newOutStream.Position = 0;
            return newOutStream;
        }

19 View Source File : MetadataProvider.cs
License : MIT License
Project Creator : afaniuolo

public T DeepCopy<T>(T item)
		{
			BinaryFormatter formatter = new BinaryFormatter();
			MemoryStream stream = new MemoryStream();
			formatter.Serialize(stream, item);
			stream.Seek(0, SeekOrigin.Begin);
			T result = (T)formatter.Deserialize(stream);
			stream.Close();
			return result;
		}

19 View Source File : Compressor.cs
License : MIT License
Project Creator : 13xforever

public virtual async Task<long> DecompressAsync(Stream source, Stream destination)
        {
            using (var memStream = new MemoryStream())
            {
                using (var decompressed = CreateDecompressionStream(source))
                    await decompressed.CopyToAsync(memStream).ConfigureAwait(false);
                memStream.Seek(0, SeekOrigin.Begin);
                await memStream.CopyToAsync(destination).ConfigureAwait(false);
                return memStream.Length;
            }
        }

19 View Source File : Mesh.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public Vertex[] DecodeVertexData()
        {
            byte[] vertexData = VertexData;
            Vertex[] vertices = new Vertex[VertexCount];

            using(MemoryStream ms = new MemoryStream(vertexData))
            {
                BinaryReader br = new BinaryReader(ms);
                for (int i = 0; i < VertexCount; i++)
                {
                    ms.Seek(i*VertexStride, SeekOrigin.Begin);
                    vertices[i] = new Vertex(br, this);
                }
            }

            return vertices;
        }

19 View Source File : ResultsInterpreter.cs
License : MIT License
Project Creator : ABN-SFLookupTechnicalSupport

public static string SerialisePayload(ServiceReferenceAbnLookupRpc.Payload searchPayload) {
         try {
            MemoryStream XmlStream = new MemoryStream();
            StreamReader XmlReader = new StreamReader(XmlStream);
            XmlSerializer Serializer = new XmlSerializer(typeof(ServiceReferenceAbnLookupRpc.Payload), ExtraTypes());
            Serializer.Serialize(XmlStream, searchPayload);
            XmlStream.Seek(0, System.IO.SeekOrigin.Begin);
            return XmlReader.ReadToEnd();
         }
         catch {
            throw;
         }
      }

19 View Source File : BundleContainer.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

public virtual byte[] Save(Stream newData) {
            var msToSave = new MemoryStream();
            var bw = new BinaryWriter(msToSave);

            uncompressed_size = (int)(size_decompressed = newData.Length);
            entry_count = uncompressed_size / chunk_size;
            if (uncompressed_size % chunk_size != 0) entry_count++;
            head_size = entry_count * 4 + 48;

            msToSave.Seek(60 + (entry_count * 4), SeekOrigin.Begin);
            newData.Seek(0, SeekOrigin.Begin);
            compressed_size = 0;
            var chunks = new int[entry_count];
            for (var i = 0; i < entry_count; i++) {
                var b = new byte[i + 1 == entry_count ? uncompressed_size - (entry_count - 1) * chunk_size : chunk_size];
                newData.Read(b, 0, b.Length);
                var by = new byte[b.Length + 548];
                var l = OodleLZ_Compress(encoder, b, b.Length, by, Compression_Level, IntPtr.Zero, 0, 0, IntPtr.Zero, 0);
                compressed_size += chunks[i] = l;
                bw.Write(by, 0, l);
            }
            size_compressed = compressed_size;

            msToSave.Seek(60, SeekOrigin.Begin);
            for (var i = 0; i < entry_count; i++)
                bw.Write(chunks[i]);

            msToSave.Seek(0, SeekOrigin.Begin);
            bw.Write(uncompressed_size);
            bw.Write(compressed_size);
            bw.Write(head_size);
            bw.Write((uint)encoder);
            bw.Write(unknown);
            bw.Write(size_decompressed);
            bw.Write(size_compressed);
            bw.Write(entry_count);
            bw.Write(chunk_size);
            bw.Write(unknown3);
            bw.Write(unknown4);
            bw.Write(unknown5);
            bw.Write(unknown6);

            bw.Flush();
            var result = msToSave.ToArray();
            bw.Close();
            return result;
        }

19 View Source File : Compressor.cs
License : MIT License
Project Creator : 13xforever

public virtual async Task<long> CompressAsync(Stream source, Stream destination)
        {
            using (var memStream = new MemoryStream())
            {
                using (var compressed = CreateCompressionStream(memStream))
                    await source.CopyToAsync(compressed).ConfigureAwait(false);
                memStream.Seek(0, SeekOrigin.Begin);
                await memStream.CopyToAsync(destination).ConfigureAwait(false);
                return memStream.Length;
            }
        }

19 View Source File : NpoiHelper.cs
License : MIT License
Project Creator : aishang2015

public MemoryStream ExportExcel<T>(
            List<T> dataList,
            Dictionary<string, string> dic,
            string sheetName = "")
        {
            var workbook = new HSSFWorkbook();
            var sheet = workbook.CreateSheet(sheetName);

            // 行下标
            var rowNum = 1;
            var replacedleRow = sheet.CreateRow(rowNum);

            // 列下标
            var colNum = 0;

            // 获取属性
            var positionDic = new Dictionary<string, int>();

            // 设置标题
            foreach (var item in dic)
            {
                replacedleRow.CreateCell(colNum).SetCellValue(item.Value);
                positionDic.Add(item.Value, colNum);
                colNum++;
            }

            // 设置内容
            rowNum++;
            var properties = typeof(T).GetProperties();
            foreach (var item in dataList)
            {
                var row = sheet.CreateRow(rowNum);
                for (int i = 0; i < properties.Length; i++)
                {
                    // 属性字典中没有该属性运行下一个属性
                    if (!dic.ContainsKey(properties[i].Name))
                    {
                        continue;
                    }

                    // 获取属性值
                    var value = properties[i].GetValue(item)?.ToString();

                    //获取对应列下标,并设定值
                    var colIndex = positionDic[dic[properties[i].Name]];
                    row.CreateCell(colIndex).SetCellValue(value);
                }
            }

            var ms = new MemoryStream();
            workbook.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);

            //return File(ms, "application/vns.ms-excel", $"{filename}"); ;
            return ms;
        }

19 View Source File : MockProjectFolder.cs
License : MIT License
Project Creator : action-bi-toolkit

public void WriteFile(string path, Action<Stream> onStreamAvailable)
        {
            using (var stream = new MemoryStream())
            {
                onStreamAvailable(stream);

                stream.Seek(0, SeekOrigin.Begin);

                using (var reader = new StreamReader(stream))
                {
                    _root.FilesStore[NormalizePath(path)] = reader.ReadToEnd();
                }
            }
        }

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private void LoadRtf(string rtf) {
			if (string.IsNullOrEmpty(rtf))
				return;

			TextRange textRange = new TextRange(previewRichTextBox.Doreplacedent.ContentStart, previewRichTextBox.Doreplacedent.ContentEnd);

			using (MemoryStream stream = new MemoryStream()) {
				using (StreamWriter writer = new StreamWriter(stream)) {
					writer.Write(rtf);
					writer.Flush();
					stream.Seek(0, SeekOrigin.Begin);

					textRange.Load(stream, DataFormats.Rtf);
				}
			}
		}

19 View Source File : DiscInfoConverter.cs
License : MIT License
Project Creator : 13xforever

public static DiscInfo ToDiscInfo(this Ird ird)
        {
            List<FileRecord> fsInfo;
            var sectorSize = 2048L;
            using (var stream = new MemoryStream())
            {
                using (var headerStream = new MemoryStream(ird.Header))
                using (var gzipStream = new GZipStream(headerStream, CompressionMode.Decompress))
                    gzipStream.CopyTo(stream);
                stream.Seek(0, SeekOrigin.Begin);
                var reader = new CDReader(stream, true, true);
                (fsInfo, _) = reader.GetFilesystemStructure();
                sectorSize = reader.ClusterSize;
            }
            var checksums = ird.Files.ToDictionary(f => f.Offset, f => f.Md5Checksum.ToHexString());
            return new DiscInfo
            {
                ProductCode = ird.ProductCode,
                DiscVersion = ird.GameVersion,
                DiscKeyRawData = ird.Data1.ToHexString(),
                DiscKey = Decrypter.DecryptDiscKey(ird.Data1).ToHexString(),
                Files = fsInfo.ToDictionary(
                    f => f.Filename,
                    f => new FileInfo
                    {
                        Offset = f.StartSector * sectorSize,
                        Size = f.Length,
                        Hashes = new Dictionary<string, string>
                        {
                            ["MD5"] = checksums[f.StartSector],
                        }
                    })
            };
        }

19 View Source File : MemoryFileAppender.cs
License : MIT License
Project Creator : adams85

public Stream CreateAppendStream(IFileInfo fileInfo)
        {
            var memoryFileInfo = (MemoryFileInfo)fileInfo;

            if (!memoryFileInfo.Exists)
                FileProvider.CreateFile(memoryFileInfo.LogicalPath);

            MemoryStream stream = FileProvider.GetStream(memoryFileInfo.LogicalPath);
            stream.Seek(0, SeekOrigin.End);
            return stream;
        }

19 View Source File : ObjectSerializationExtension.cs
License : MIT License
Project Creator : 734843327

public static T Deserialize<T>(this byte[] byteArray) where T : clreplaced
		{
			if (byteArray == null)
			{
				return null;
			}
			using (var memStream = new MemoryStream())
			{
				var binForm = new BinaryFormatter();
				memStream.Write(byteArray, 0, byteArray.Length);
				memStream.Seek(0, SeekOrigin.Begin);
				var obj = (T)binForm.Deserialize(memStream);
				return obj;
			}
		}

19 View Source File : MemoryIterator.cs
License : Apache License 2.0
Project Creator : aequabit

public long Seek(long offset, SeekOrigin origin)
        {
            return this._base.Seek(offset, origin);
        }

19 View Source File : HttpHelper.cs
License : GNU General Public License v3.0
Project Creator : aduskin

static WebList Http_DownSteam(HttpWebResponse response, Encoding encoding)
      {
         WebList _web = new WebList
         {
            Encoding = encoding,
            StatusCode = (int)response.StatusCode,
            Type = response.ContentType,
            AbsoluteUri = response.ResponseUri.AbsoluteUri
         };
         string header = "";
         foreach (string str in response.Headers.AllKeys)
         {
            if (str == "Set-Cookie")
            {
               _web.SetCookie = response.Headers[str];
            }
            else if (str == "Location")
            {
               _web.Location = response.Headers[str];
            }
            header = header + str + ":" + response.Headers[str] + "\r\n";
         }
         string cookie = "";
         foreach (Cookie str in response.Cookies)
         {
            cookie = cookie + str.Name + "=" + str.Value + ";";
         }

         _web.Header = header;
         _web.Cookie = cookie;

         #region 下载流
         using (Stream stream = response.GetResponseStream())
         {
            using (MemoryStream file = new MemoryStream())
            {
               int _value = 0;
               byte[] _cache = new byte[1024];
               int osize = stream.Read(_cache, 0, 1024);

               while (osize > 0)
               {
                  _value += osize;

                  file.Write(_cache, 0, osize);
                  osize = stream.Read(_cache, 0, 1024);
               }

               file.Seek(0, SeekOrigin.Begin);
               byte[] _byte = new byte[_value];
               file.Read(_byte, 0, _value);

               file.Seek(0, SeekOrigin.Begin);
               string fileclreplaced = GetFileClreplaced(file);
               if (fileclreplaced == "31139")
               {
                  //_web.OriginalSize = _byte.Length;
                  _web.Byte = Decompress(_byte);
               }
               else
               {
                  _web.Byte = _byte;
               }
            }
         }
         #endregion
         return _web;
      }

19 View Source File : SevenZipHelper.cs
License : MIT License
Project Creator : 91Act

public static MemoryStream StreamDecompress(MemoryStream newInStream)
        {
            Decoder decoder = new Decoder();

            newInStream.Seek(0, 0);
            MemoryStream newOutStream = new MemoryStream();

            byte[] properties2 = new byte[5];
            if (newInStream.Read(properties2, 0, 5) != 5)
                throw (new Exception("input .lzma is too short"));
            long outSize = 0;
            for (int i = 0; i < 8; i++)
            {
                int v = newInStream.ReadByte();
                if (v < 0)
                    throw (new Exception("Can't Read 1"));
                outSize |= ((long)(byte)v) << (8 * i);
            }
            decoder.SetDecoderProperties(properties2);

            long compressedSize = newInStream.Length - newInStream.Position;
            decoder.Code(newInStream, newOutStream, compressedSize, outSize, null);

            newOutStream.Position = 0;
            return newOutStream;
        }

19 View Source File : MemoryIterator.cs
License : Apache License 2.0
Project Creator : aequabit

public bool Read<TResult>(long offset, SeekOrigin origin, out TResult result) where TResult: struct
        {
            result = default(TResult);
            try
            {
                this._base.Seek(offset, origin);
                byte[] buffer = new byte[Marshal.SizeOf(typeof(TResult))];
                this._base.Read(buffer, 0, buffer.Length);
                if (!this._ubuffer.Translate<TResult>(buffer, out result))
                {
                    throw this._ubuffer.GetLastError();
                }
                return true;
            }
            catch (Exception exception)
            {
                return base.SetLastError(exception);
            }
        }

19 View Source File : ProxyGenerator.cs
License : MIT License
Project Creator : 1100100

private static MemoryStream Compile(string replacedemblyName, IEnumerable<SyntaxTree> trees, IEnumerable<MetadataReference> references)
        {
            var compilation = CSharpCompilation.Create(replacedemblyName, trees, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
            var stream = new MemoryStream();
            var result = compilation.Emit(stream);
            if (!result.Success)
            {
                throw new Exception("Generate dynamic proxy failed:\n" + string.Join(";\n", result.Diagnostics.Select(i => i.ToString())));
            }
            stream.Seek(0, SeekOrigin.Begin);
            return stream;
        }

19 View Source File : MemoryIterator.cs
License : Apache License 2.0
Project Creator : aequabit

public bool Write(long offset, SeekOrigin origin, byte[] data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("Parameter 'data' cannot be null");
            }
            try
            {
                this._base.Seek(offset, origin);
                this._base.Write(data, 0, data.Length);
                return true;
            }
            catch (Exception exception)
            {
                return this.SetLastError(exception);
            }
        }

19 View Source File : GZip.cs
License : Apache License 2.0
Project Creator : AantCoder

public static byte[] ZipObjByte(object obj)
        {
            using (var msi = new MemoryStream())
            {
                if (formatter == null) formatter = new BinaryFormatter();
                formatter.Serialize(msi, obj);
                LastSizeObj = msi.Length;
                msi.Seek(0, SeekOrigin.Begin);
                return ZipStreamByte(msi);
            }
        }

19 View Source File : IOHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string XMLSerializer<T>(T args)
        {
            if (Equals(args,default(T)))
                return null;
            using (var ms = new MemoryStream())
            {
                var ds = new DataContractSerializer(typeof(T));
                ds.WriteObject(ms, args);
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);
                var sr = new StreamReader(ms);
                return sr.ReadToEnd();
            }
        }

19 View Source File : XnaToFnaUtil.cs
License : zlib License
Project Creator : 0x0ade

public void ScanPath(string path) {
            if (Directory.Exists(path)) {
                // Use the directory as "dependency directory" and scan in it.
                if (Directories.Contains(path))
                    // No need to scan the dir if the dir is scanned...
                    return;

                RestoreBackup(path);

                Log($"[ScanPath] Scanning directory {path}");
                Directories.Add(path);
                replacedemblyResolver.AddSearchDirectory(path); // Needs to be added manually as DependencyDirs was already added

                // Most probably the actual game directory - let's just copy XnaToFna.exe to there to be referenced properly.
                string xtfPath = Path.Combine(path, Path.GetFileName(Thisreplacedembly.Location));
                if (Path.GetDirectoryName(Thisreplacedembly.Location) != path) {
                    Log($"[ScanPath] Found separate game directory - copying XnaToFna.exe and FNA.dll");
                    File.Copy(Thisreplacedembly.Location, xtfPath, true);

                    string dbExt = null;
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "pdb")))
                        dbExt = "pdb";
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "mdb")))
                        dbExt = "mdb";
                    if (dbExt != null)
                        File.Copy(Path.ChangeExtension(Thisreplacedembly.Location, dbExt), Path.ChangeExtension(xtfPath, dbExt), true);

                    if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll"), Path.Combine(path, "FNA.dll"), true);
                    else if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp"), Path.Combine(path, "FNA.dll"), true);

                }

                ScanPaths(Directory.GetFiles(path));
                return;
            }

            if (File.Exists(path + ".xex")) {
                if (!ExtractedXEX.Contains(path)) {
                    // Remove the original file - let XnaToFna unpack and handle it later.
                    File.Delete(path);
                } else {
                    // XnaToFna will handle the .xex instead.
                }
                return;
            }

            if (path.EndsWith(".xex")) {
                string pathTarget = path.Substring(0, path.Length - 4);
                if (string.IsNullOrEmpty(Path.GetExtension(pathTarget)))
                    return;

                using (Stream streamXEX = File.OpenRead(path))
                using (BinaryReader reader = new BinaryReader(streamXEX))
                using (Stream streamRAW = File.OpenWrite(pathTarget)) {
                    XEXImageData data = new XEXImageData(reader);

                    int offset = 0;
                    int size = data.m_memorySize;

                    // Check if this file is a PE containing an embedded PE.
                    if (data.m_memorySize > 0x10000) { // One default segment alignment.
                        using (MemoryStream streamMEM = new MemoryStream(data.m_memoryData))
                        using (BinaryReader mem = new BinaryReader(streamMEM)) {
                            if (mem.ReadUInt32() != 0x00905A4D) // MZ
                                goto WriteRaw;
                            // This is horrible.
                            streamMEM.Seek(0x00000280, SeekOrigin.Begin);
                            if (mem.ReadUInt64() != 0x000061746164692E) // ".idata\0\0"
                                goto WriteRaw;
                            streamMEM.Seek(0x00000288, SeekOrigin.Begin);
                            mem.ReadInt32(); // Virtual size; It's somewhat incorrect?
                            offset = mem.ReadInt32(); // Virtual offset.
                            // mem.ReadInt32(); // Raw size; Still incorrect.
                            // Let's just write everything...
                            size = data.m_memorySize - offset;
                        }
                    }

                    WriteRaw:
                    streamRAW.Write(data.m_memoryData, offset, size);
                }

                path = pathTarget;
                ExtractedXEX.Add(pathTarget);
            } else if (!path.EndsWith(".dll") && !path.EndsWith(".exe"))
                return;

            // Check if .dll is CLR replacedembly
            replacedemblyName name;
            try {
                name = replacedemblyName.GetreplacedemblyName(path);
            } catch {
                return;
            }

            ReaderParameters modReaderParams = Modder.GenReaderParameters(false);
            // Don't ReadWrite if the module being read is XnaToFna or a relink target.
            bool isReadWrite =
#if !CECIL0_9
            modReaderParams.ReadWrite =
#endif
                path != Thisreplacedembly.Location &&
                !Mappings.Exists(mappings => name.Name == mappings.Target);
            // Only read debug info if it exists
            if (!File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb")))
                modReaderParams.ReadSymbols = false;
            Log($"[ScanPath] Checking replacedembly {name.Name} ({(isReadWrite ? "rw" : "r-")})");
            ModuleDefinition mod;
            try {
                mod = MonoModExt.ReadModule(path, modReaderParams);
            } catch (Exception e) {
                Log($"[ScanPath] WARNING: Cannot load replacedembly: {e}");
                return;
            }
            bool add = !isReadWrite || name.Name == ThisreplacedemblyName;

            if ((mod.Attributes & ModuleAttributes.ILOnly) != ModuleAttributes.ILOnly) {
                // Mono.Cecil can't handle mixed mode replacedemblies.
                Log($"[ScanPath] WARNING: Cannot handle mixed mode replacedembly {name.Name}");
                if (MixedDeps == MixedDepAction.Stub) {
                    ModulesToStub.Add(mod);
                    add = true;
                } else {
                    if (MixedDeps == MixedDepAction.Remove) {
                        RemoveDeps.Add(name.Name);
                    }
#if !CECIL0_9
                    mod.Dispose();
#endif
                    return;
                }
            }

            if (add && !isReadWrite) { // XNA replacement
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (name.Name == mapping.Target) {
                        mapping.IsActive = true;
                        mapping.Module = mod;
                        foreach (string from in mapping.Sources) {
                            Log($"[ScanPath] Mapping {from} -> {name.Name}");
                            Modder.RelinkModuleMap[from] = mod;
                        }
                    }
            } else if (!add) {
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (mod.replacedemblyReferences.Any(dep => mapping.Sources.Contains(dep.Name))) {
                        add = true;
                        Log($"[ScanPath] XnaToFna-ing {name.Name}");
                        goto BreakMappings;
                    }
            }
            BreakMappings:

            if (add) {
                Modules.Add(mod);
                ModulePaths[mod] = path;
            } else {
#if !CECIL0_9
                mod.Dispose();
#endif
            }

        }

19 View Source File : ZeroPublishExtend.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static bool Publish<T>(this ZSocket socket, string replacedle, string subreplacedle, T content)
            where T : clreplaced
        {
            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
            byte[] buffer;
            using (MemoryStream ms = new MemoryStream())
            {
                js.WriteObject(ms, content);
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);
                buffer = ms.ToArray();
            }
            return subreplacedle == null
                ? Publish(socket, PubDescriptionData, replacedle, buffer)
                : Publish(socket, PubDescriptionData2, replacedle, subreplacedle, buffer);
        }

19 View Source File : ResultsInterpreter.cs
License : MIT License
Project Creator : ABN-SFLookupTechnicalSupport

public static string SerialisePayload(ServiceReferenceAbnLookup.Payload searchPayload) {
         try {
            MemoryStream XmlStream = new MemoryStream();
            StreamReader XmlReader = new StreamReader(XmlStream);
            XmlSerializer Serializer = new XmlSerializer(typeof(ServiceReferenceAbnLookup.Payload));
            Serializer.Serialize(XmlStream, searchPayload);
            XmlStream.Seek(0, System.IO.SeekOrigin.Begin);
            return XmlReader.ReadToEnd();
         }
         catch {
            throw;
         }
      }

19 View Source File : ResourceFile.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public void Read(Stream data)
        {
            _header = new ResourceHeader();

            var br = new BinaryReader(data);
            _header.Read(br);
            if (_header.Magic != ResourceHeader.MagicValue)
            {
                throw new Exception("Not a valid resource");
            }

            switch (_header.CompressCodec)
            {
                case CompressionType.LZX:
                    _codec = CompressionCodecFactory.LZX;
                    break;
                case CompressionType.Deflate:
                    _codec = CompressionCodecFactory.Deflate;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            var ms = new MemoryStream();
            _codec.Decompress( data, ms );

            ms.Seek(0, SeekOrigin.Begin);

            _systemMemData = new byte[SystemMemSize];
            ms.Read(_systemMemData, 0, SystemMemSize);

            _graphicsMemData = new byte[GraphicsMemSize];
            ms.Read(_graphicsMemData, 0, GraphicsMemSize);

            ms.Close();
        }

19 View Source File : StreamDeserializeAuxTest.cs
License : MIT License
Project Creator : 1996v

[Theory]
        [InlineData(typeof(sbyte))]
        [InlineData(typeof(Int16))]
        [InlineData(typeof(Int32))]
        [InlineData(typeof(Int64))]
        [InlineData(typeof(byte))]
        [InlineData(typeof(UInt16))]
        [InlineData(typeof(UInt32))]
        [InlineData(typeof(UInt64))]
        [InlineData(typeof(Char))]
        [InlineData(typeof(Boolean))]
        [InlineData(typeof(Single))]
        [InlineData(typeof(Double))]
        [InlineData(typeof(string))]
        [InlineData(typeof(Guid))]
        [InlineData(typeof(DateTime))]
        [InlineData(typeof(Decimal))]

        [InlineData(typeof(Dictionary<sbyte, List<object>>))]
        [InlineData(typeof(Dictionary<Int16, List<object>>))]
        [InlineData(typeof(Dictionary<Int32, List<object>>))]
        [InlineData(typeof(Dictionary<Int64, List<object>>))]
        [InlineData(typeof(Dictionary<byte, List<object>>))]
        [InlineData(typeof(Dictionary<UInt16, List<object>>))]
        [InlineData(typeof(Dictionary<UInt32, List<object>>))]
        [InlineData(typeof(Dictionary<UInt64, List<object>>))]
        [InlineData(typeof(Dictionary<Char, List<object>>))]
        [InlineData(typeof(Dictionary<Boolean, List<object>>))]
        [InlineData(typeof(Dictionary<Single, List<object>>))]
        [InlineData(typeof(Dictionary<Double, List<object>>))]
        [InlineData(typeof(Dictionary<string, List<object>>))]
        [InlineData(typeof(Dictionary<Guid, List<object>>))]
        [InlineData(typeof(Dictionary<DateTime, List<object>>))]
        [InlineData(typeof(Dictionary<Decimal, List<object>>))]

        [InlineData(typeof(List<byte>))]
        [InlineData(typeof(List<int>))]
        [InlineData(typeof(List<DateTime>))]
        [InlineData(typeof(List<string>))]
        [InlineData(typeof(List<object>))]
        [InlineData(typeof(List<List<object>>))]

        [InlineData(typeof(byte[]))]
        [InlineData(typeof(char[]))]
        [InlineData(typeof(double[]))]
        [InlineData(typeof(DateTime[]))]
        [InlineData(typeof(string[]))]
        [InlineData(typeof(object[]))]

        [InlineData(typeof(ArraySegment<byte>))]
        [InlineData(typeof(ArraySegment<decimal>))]
        [InlineData(typeof(ArraySegment<ulong>))]
        [InlineData(typeof(ArraySegment<DateTime>))]
        [InlineData(typeof(ArraySegment<string>))]
        [InlineData(typeof(ArraySegment<object>))]

        [InlineData(typeof(_clreplaced1))]
        [InlineData(typeof(_clreplaced2))]
        [InlineData(typeof(_clreplaced3))]
        public void ReadOneObjectBytesFromStreamIsCorrectly(Type type)
        {
            var obj = RandomHelper.RandomValueWithOutStringEmpty(type);
            var buf = BssomSerializer.Serialize(obj);
            var stream = new MemoryStream(buf);

            var sda = new StreamDeserializeAux(stream);
            var bssomBuf = sda.GetBssomBuffer();
            ref byte refb = ref bssomBuf.ReadRef(buf.Length);

            SequenceEqual(buf,ref refb,buf.Length);
        
            stream.Seek(0, SeekOrigin.Begin);
            var sda2 = new StreamDeserializeAux(stream);
            ref byte refb2 = ref sda.GetBssomBufferAsync().Result.ReadRef(buf.Length);
            SequenceEqual(buf, ref refb2, buf.Length);
        }

19 View Source File : AudioPlayer.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

private void Filler(IntPtr data, int size)
        {
            int blockCount = _wave.BlockCount;
            byte[] b = new byte[size];

            if (_file != null && (_looped || _lastBlock < blockCount))
            {
                MemoryStream ms = new MemoryStream();

                if (_leftOverBuffer != null)
                {
                    ms.Write(_leftOverBuffer, 0, _leftOverBuffer.Length);
                }
                
                while (ms.Position < size)
                {
                    _lastBlock++;

                    if (_lastBlock >= blockCount)
                    {
                        if (!_looped)
                        {
                            while(ms.Position < size)
                            {
                                ms.WriteByte(0);
                            }
                            break;
                        }
                        else
                        {
                            _lastBlock = 0;
                            _state = new DviAdpcmDecoder.AdpcmState();
                        }
                    }

                    _file.SoundBank.ExportWaveBlockAsPCM(_wave.Index, _lastBlock, ref _state, _file.Stream, ms);
                }

                int extraData = (int)(ms.Position - size);
                
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(b, 0, size);

                if (extraData > 0)
                {
                    _leftOverBuffer = new byte[extraData];
                    ms.Read(_leftOverBuffer, 0, extraData);
                }
                else
                {
                    _leftOverBuffer = null;
                }
            }
            else
            {
                for (int i = 0; i < b.Length; i++)
                {
                    b[i] = 0;
                }
            }
            System.Runtime.InteropServices.Marshal.Copy(b, 0, data, size);
        }

19 View Source File : Export-CrmDataPackage.cs
License : MIT License
Project Creator : abvogel

protected override void ProcessRecord()
        {
            try
            {
                using (ZipFile zip = new ZipFile())
                {
                    GenerateVerboseMessage("Streaming [Content_Types].xml to memory.");
                    MemoryStream contentTypeFS = new MemoryStream();
                    Package.ContentTypes.Save(contentTypeFS);
                    contentTypeFS.Seek(0, SeekOrigin.Begin);

                    GenerateVerboseMessage("Streaming data.xml to memory.");
                    MemoryStream dataFS = new MemoryStream();
                    Package.Data.Save(dataFS);
                    dataFS.Seek(0, SeekOrigin.Begin);

                    GenerateVerboseMessage("Streaming data_schema.xml to memory.");
                    MemoryStream schemaFS = new MemoryStream();
                    Package.Schema.Save(schemaFS);
                    schemaFS.Seek(0, SeekOrigin.Begin);

                    GenerateVerboseMessage("Crossing the streams.");
                    zip.AddEntry("[Content_Types].xml", contentTypeFS);
                    zip.AddEntry("data.xml", dataFS);
                    zip.AddEntry("data_schema.xml", schemaFS);

                    GenerateVerboseMessage(String.Format("Zipping streams to {0}.", ZipPath));
                    zip.Save(ZipPath);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

19 View Source File : BundleContainer.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

public virtual byte[] AppendAndSave(Stream newData, Stream originalData) {
            originalData.Seek(offset + 60, SeekOrigin.Begin);
            var OldChunkCompressedSizes = new byte[(entry_count - 1) * 4];
            originalData.Read(OldChunkCompressedSizes, 0, OldChunkCompressedSizes.Length);

            var lastCunkCompressedSize = originalData.ReadByte() | originalData.ReadByte() << 8 | originalData.ReadByte() << 16 | originalData.ReadByte() << 24; //ReadInt32

            var lastCunkDecompressedSize = uncompressed_size - (chunk_size * (entry_count - 1));

            uncompressed_size = (int)(size_decompressed += newData.Length);
            entry_count = uncompressed_size / chunk_size;
            if (uncompressed_size % chunk_size != 0) entry_count++;
            head_size = entry_count * 4 + 48;

            var msToSave = new MemoryStream();
            var bw = new BinaryWriter(msToSave);

            msToSave.Seek(60 + (entry_count * 4), SeekOrigin.Begin);
            var o = new byte[compressed_size - lastCunkCompressedSize];
            originalData.Read(o, 0, o.Length);
            bw.Write(o);

            var lastChunkCompressedData = new byte[lastCunkCompressedSize];
            originalData.Read(lastChunkCompressedData, 0, lastCunkCompressedSize);
            var lastCunkDecompressedData = new byte[lastCunkDecompressedSize + 64];
			_ = OodleLZ_Decompress(lastChunkCompressedData, lastCunkCompressedSize, lastCunkDecompressedData, lastCunkDecompressedSize, 0, 0, 0, IntPtr.Zero, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0, 3);

            newData.Seek(0, SeekOrigin.Begin);
            compressed_size -= lastCunkCompressedSize;
            var NewChunkCompressedSizes = new int[entry_count - (OldChunkCompressedSizes.Length / 4)];

            var FirstNewDataChunk = new byte[Math.Min(chunk_size - lastCunkDecompressedSize, newData.Length)];
            newData.Read(FirstNewDataChunk, 0, FirstNewDataChunk.Length);
            FirstNewDataChunk = lastCunkDecompressedData.Take(lastCunkDecompressedSize).Concat(FirstNewDataChunk).ToArray();
            var CompressedChunk = new byte[FirstNewDataChunk.Length + 548];
            var CompressedLength = OodleLZ_Compress(encoder, FirstNewDataChunk, FirstNewDataChunk.Length, CompressedChunk, Compression_Level, IntPtr.Zero, 0, 0, IntPtr.Zero, 0);
            compressed_size += NewChunkCompressedSizes[0] = CompressedLength;
            bw.Write(CompressedChunk, 0, CompressedLength);
            for (var i = 1; i < NewChunkCompressedSizes.Length; i++) {
                var size = (i + 1 == NewChunkCompressedSizes.Length) ? uncompressed_size - (chunk_size * (entry_count - 1)) : chunk_size;
                var b = new byte[size];
                newData.Read(b, 0, size);
                var by = new byte[b.Length + 548];
                var l = OodleLZ_Compress(encoder, b, size, by, Compression_Level, IntPtr.Zero, 0, 0, IntPtr.Zero, 0);
                compressed_size += NewChunkCompressedSizes[i] = l;
                bw.Write(by, 0, l);
            }
            size_compressed = compressed_size;

            msToSave.Seek(60, SeekOrigin.Begin);
            bw.Write(OldChunkCompressedSizes);
            for (var i = 0; i < NewChunkCompressedSizes.Length; i++)
                bw.Write(NewChunkCompressedSizes[i]);

            msToSave.Seek(0, SeekOrigin.Begin);
            bw.Write(uncompressed_size);
            bw.Write(compressed_size);
            bw.Write(head_size);
            bw.Write((uint)encoder);
            bw.Write(unknown);
            bw.Write(size_decompressed);
            bw.Write(size_compressed);
            bw.Write(entry_count);
            bw.Write(chunk_size);
            bw.Write(unknown3);
            bw.Write(unknown4);
            bw.Write(unknown5);
            bw.Write(unknown6);

            bw.Flush();
            var result = msToSave.ToArray();
            bw.Close();
            return result;
        }

19 View Source File : SqliteUserData.cs
License : MIT License
Project Creator : 0x0ade

public override Stream WriteFile(string uid, string name) {
            MemoryStream ms = new();
            return new DisposeActionStream(ms, () => {
                ms.Seek(0, SeekOrigin.Begin);

                using UserDataBatchContext batch = OpenBatch();
                string table = GetFileTable(name, true);
                using MiniCommand mini = new(this) {
                    SqliteOpenMode.ReadWrite,
                    EnsureExistsQuery + @$"
                        REPLACE INTO [{table}] (uid, value)
                        VALUES ($uid, zeroblob($length));

                        SELECT _ROWID_
                        FROM [{table}]
                        WHERE uid = $uid;
                    ",
                    { "$uid", uid },
                    { "$length", ms.Length },
                };

19 View Source File : ImageCompressEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static Bitmap _MakeTransparentGif(Bitmap bitmap, Color color)
		{
			byte R = color.R;
			byte G = color.G;
			byte B = color.B;

			MemoryStream fin = new MemoryStream();
			bitmap.Save(fin, System.Drawing.Imaging.ImageFormat.Gif);

			MemoryStream fout = new MemoryStream((int)fin.Length);
			int count = 0;
			byte[] buf = new byte[256];
			byte transparentIdx = 0;
			fin.Seek(0, SeekOrigin.Begin);
			//header
			count = fin.Read(buf, 0, 13);
			if ((buf[0] != 71) || (buf[1] != 73) || (buf[2] != 70)) return null; //GIF

			fout.Write(buf, 0, 13);

			int i = 0;
			if ((buf[10] & 0x80) > 0)
			{
				i = 1 << ((buf[10] & 7) + 1) == 256 ? 256 : 0;
			}

			for (; i != 0; i--)
			{
				fin.Read(buf, 0, 3);
				if ((buf[0] == R) && (buf[1] == G) && (buf[2] == B))
				{
					//transparentIdx = (byte)(256 - i);
				}
				fout.Write(buf, 0, 3);
			}

			bool gcePresent = false;
			while (true)
			{
				fin.Read(buf, 0, 1);
				fout.Write(buf, 0, 1);
				if (buf[0] != 0x21) 
					break;
				fin.Read(buf, 0, 1);
				fout.Write(buf, 0, 1);
				gcePresent = (buf[0] == 0xf9);
				while (true)
				{
					fin.Read(buf, 0, 1);
					fout.Write(buf, 0, 1);
					if (buf[0] == 0) 
						break;
					count = buf[0];
					if (fin.Read(buf, 0, count) != count) return null;
					if (gcePresent)
					{
						if (count == 4)
						{
							buf[0] |= 0x01;
							buf[3] = transparentIdx;
						}
					}
					fout.Write(buf, 0, count);
				}
			}
			while (count > 0)
			{
				count = fin.Read(buf, 0, 1);
				fout.Write(buf, 0, 1);
			}
			fin.Close();
			fout.Flush();

			return new Bitmap(fout);
		}

19 View Source File : FileExplorer.xaml.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

public void ReadPortalFile(uint fileID)
        {
            switch (fileID >> 24)
            {
                case 0x01:
                    var gfxObj = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.GfxObj>(fileID);
                    FileInfo.SetInfo(new FileTypes.GfxObj(gfxObj).BuildTree());
                    GameView.ViewMode = ViewMode.Model;
                    ModelViewer.LoadModel(fileID);
                    break;
                case 0x02:
                    var setup = DatManager.PortalDat.ReadFromDat<SetupModel>(fileID);
                    FileInfo.SetInfo(new Setup(setup).BuildTree());
                    GameView.ViewMode = ViewMode.Model;
                    ModelViewer.LoadModel(fileID);
                    MotionList.OnClickSetup(fileID);
                    break;
                case 0x03:
                    var anim = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.Animation>(fileID);
                    FileInfo.SetInfo(new FileTypes.Animation(anim).BuildTree());
                    break;
                case 0x04:
                    var palette = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.Palette>(fileID);
                    FileInfo.SetInfo(new FileTypes.Palette(palette).BuildTree());
                    GameView.ViewMode = ViewMode.Texture;
                    TextureViewer.LoadTexture(fileID);
                    if (TextureViewer.CurScale < PaletteScale)
                        TextureViewer.SetScale(PaletteScale);
                    break;
                case 0x05:
                    var surfaceTexture = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.SurfaceTexture>(fileID);
                    FileInfo.SetInfo(new FileTypes.SurfaceTexture(surfaceTexture).BuildTree());
                    GameView.ViewMode = ViewMode.Texture;
                    TextureViewer.LoadTexture(fileID);
                    break;
                case 0x06:
                    var texture = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.Texture>(fileID);
                    FileInfo.SetInfo(new FileTypes.Texture(texture).BuildTree());
                    GameView.ViewMode = ViewMode.Texture;
                    TextureViewer.LoadTexture(fileID);
                    break;
                case 0x08:
                    var surface = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.Surface>(fileID);
                    FileInfo.SetInfo(new FileTypes.Surface(surface).BuildTree(fileID));
                    GameView.ViewMode = ViewMode.Texture;
                    TextureViewer.LoadTexture(fileID);
                    break;
                case 0x09:
                    var motionTable = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.MotionTable>(fileID);
                    FileInfo.SetInfo(new FileTypes.MotionTable(motionTable).BuildTree());
                    break;
                case 0x0A:
                    var sound = DatManager.PortalDat.ReadFromDat<Wave>(fileID);
                    FileInfo.SetInfo(new FileTypes.Sound(sound).BuildTree(fileID));
                    var stream = new MemoryStream();
                    sound.ReadData(stream);
                    var soundPlayer = new SoundPlayer(stream);
                    stream.Seek(0, SeekOrigin.Begin);
                    soundPlayer.Play();
                    stream.Close();
                    break;
                case 0x0D:
                    var environment = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.Environment>(fileID);
                    FileInfo.SetInfo(new FileTypes.Environment(environment).BuildTree());
                    GameView.ViewMode = ViewMode.Model;
                    ModelViewer.LoadEnvironment(fileID);
                    break;
                case 0x0E:
                    if (fileID == 0x0E000002)
                    {
                        var charGen = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.CharGen>(fileID);
                        FileInfo.SetInfo(new FileTypes.CharGen(charGen).BuildTree());
                    }
                    else if (fileID == 0x0E000003)
                    {
                        var vitalTable = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.SecondaryAttributeTable>(fileID);
                        FileInfo.SetInfo(new FileTypes.SecondaryAttributeTable(vitalTable).BuildTree());
                    }
                    else if (fileID == 0x0E000004)
                    {
                        var skillTable = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.SkillTable>(fileID);
                        FileInfo.SetInfo(new FileTypes.SkillTable(skillTable).BuildTree());
                    }
                    else if (fileID == 0x0E000007)
                    {
                        var chatPoseTable = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.ChatPoseTable>(fileID);
                        FileInfo.SetInfo(new FileTypes.ChatPoseTable(chatPoseTable).BuildTree());
                    }
                    else if (fileID == 0x0E00000D)
                    {
                        var generatorTable = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.GeneratorTable>(fileID);
                        FileInfo.SetInfo(new FileTypes.GeneratorTable(generatorTable).BuildTree());
                    }
                    else if (fileID == 0x0E00000E)
                    {
                        var spellTable = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.SpellTable>(fileID);
                        FileInfo.SetInfo(new FileTypes.SpellTable(spellTable).BuildTree());
                    }
                    else if (fileID == 0x0E00000F)
                    {
                        var spellComponentsTable = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.SpellComponentsTable>(fileID);
                        FileInfo.SetInfo(new FileTypes.SpellComponentsTable(spellComponentsTable).BuildTree());
                    }
                    else if (fileID == 0x0E000018)
                    {
                        var xpTable = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.XpTable>(fileID);
                        FileInfo.SetInfo(new FileTypes.XpTable(xpTable).BuildTree());
                    }
                    else if (fileID == 0x0E00001A)
                    {
                        var badData = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.BadData>(fileID);
                        FileInfo.SetInfo(new FileTypes.BadData(badData).BuildTree());
                    }
                    else if (fileID == 0x0E00001D)
                    {
                        var contractTable = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.ContractTable>(fileID);
                        FileInfo.SetInfo(new FileTypes.ContractTable(contractTable).BuildTree());
                    }
                    else if (fileID == 0x0E00001E)
                    {
                        var tabooTable = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.TabooTable>(fileID);
                        FileInfo.SetInfo(new FileTypes.TabooTable(tabooTable).BuildTree());
                    }
                    else if (fileID == 0x0E000020)
                    {
                        var nameFilterTable = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.NameFilterTable>(fileID);
                        FileInfo.SetInfo(new FileTypes.NameFilterTable(nameFilterTable).BuildTree());
                    }
                    break;
                case 0x0F:
                    var paletteSet = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.PaletteSet>(fileID);
                    FileInfo.SetInfo(new FileTypes.PaletteSet(paletteSet).BuildTree());
                    GameView.ViewMode = ViewMode.Texture;
                    TextureViewer.LoadTexture(fileID);
                    if (TextureViewer.CurScale < PaletteScale / 2.0f)
                        TextureViewer.SetScale(PaletteScale / 2.0f);
                    break;
                case 0x10:
                    var clothing = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.ClothingTable>(fileID);
                    FileInfo.SetInfo(new FileTypes.ClothingTable(clothing).BuildTree());
                    GameView.ViewMode = ViewMode.Model;
                    ClothingTableList.OnClickClothingBase(clothing, fileID);
                    break;
                case 0x11:
                    var degradeInfo = DatManager.PortalDat.ReadFromDat<GfxObjDegradeInfo>(fileID);
                    FileInfo.SetInfo(new DegradeInfo(degradeInfo).BuildTree());
                    break;
                case 0x12:
                    var scene = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.Scene>(fileID);
                    FileInfo.SetInfo(new FileTypes.Scene(scene).BuildTree());
                    break;
                case 0x13:
                    var region = DatManager.PortalDat.ReadFromDat<RegionDesc>(fileID);
                    FileInfo.SetInfo(new Region(region).BuildTree());
                    break;
                case 0x20:
                    var soundTable = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.SoundTable>(fileID);
                    FileInfo.SetInfo(new FileTypes.SoundTable(soundTable).BuildTree());
                    break;
                case 0x22:
                    var enumMapper = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.EnumMapper>(fileID);
                    FileInfo.SetInfo(new FileTypes.EnumMapper(enumMapper).BuildTree());
                    break;
                case 0x23:
                    var stringTable = DatManager.LanguageDat.ReadFromDat<ACE.DatLoader.FileTypes.StringTable>(fileID);
                    FileInfo.SetInfo(new FileTypes.StringTable(stringTable).BuildTree());
                    break;
                case 0x25:
                    var didMapper = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.DidMapper>(fileID);
                    FileInfo.SetInfo(new FileTypes.DidMapper(didMapper).BuildTree());
                    break;
                case 0x27:
                    var dualDidMapper = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.DualDidMapper>(fileID);
                    FileInfo.SetInfo(new FileTypes.DualDidMapper(dualDidMapper).BuildTree());
                    break;
                case 0x30:
                    var combatTable = DatManager.PortalDat.ReadFromDat<CombatManeuverTable>(fileID);
                    FileInfo.SetInfo(new CombatTable(combatTable).BuildTree());
                    break;
                case 0x32:
                    var emitterInfo = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.ParticleEmitterInfo>(fileID);
                    FileInfo.SetInfo(new FileTypes.ParticleEmitterInfo(emitterInfo).BuildTree());
                    ParticleViewer.Instance.InitEmitter(fileID, 1.0f);
                    break;
                case 0x33:
                    var playScript = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.PhysicsScript>(fileID);
                    FileInfo.SetInfo(new FileTypes.PhysicsScript(playScript).BuildTree());
                    ParticleViewer.Instance.InitEmitter(fileID, 1.0f);
                    break;
                case 0x34:
                    var pScriptTable = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.PhysicsScriptTable>(fileID);
                    FileInfo.SetInfo(new FileTypes.PhysicsScriptTable(pScriptTable).BuildTree());
                    ScriptList.Instance.ScriptTable_OnClick(fileID);
                    break;
            }
        }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static T DeepCopy<T>(T obj)
        {
            object retval;
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();
                //序列化成流
                bf.Serialize(ms, obj);
                ms.Seek(0, SeekOrigin.Begin);
                //反序列化成对象
                retval = bf.Deserialize(ms);
                ms.Close();
            }
            return (T)retval;
        }

19 View Source File : SqliteUserData.cs
License : MIT License
Project Creator : 0x0ade

public override Stream? ReadFile(string uid, string name) {
            using UserDataBatchContext batch = OpenBatch();
            string table = GetFileTable(name, false);
            if (table.IsNullOrEmpty())
                return null;
            using MiniCommand mini = new(this) {
                SqliteOpenMode.ReadOnly,
                @$"
                    SELECT value
                    FROM [{table}]
                    WHERE uid = $uid
                    LIMIT 1;
                ",
                { "$uid", uid },
            };
            (SqliteConnection con, SqliteCommand cmd, SqliteDataReader reader) = mini.Read();

            if (!reader.Read())
                return null;

            Stream stream = reader.GetStream(0);
            if (stream is MemoryStream ms)
                return ms;

            ms = new MemoryStream();
            using (stream)
                stream.CopyTo(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return ms;
        }

19 View Source File : CelesteNetUtils.cs
License : MIT License
Project Creator : 0x0ade

public static byte[] ToBytes(this Stream stream) {
            if (stream is MemoryStream ms)
                return ms.ToArray();

            long length;
            if (stream.CanSeek) {
                try {
                    length = stream.Length - stream.Position;
                } catch {
                    length = 0;
                }
            } else {
                length = 0;
            }

            if (length != 0) {
                byte[] data = new byte[length];
                using (ms = new MemoryStream(data, 0, (int) length, true, true)) {
                    stream.CopyTo(ms);
                }
                return data;
            }

            using (ms = new()) {
                stream.CopyTo(ms);
                length = ms.Position;
                ms.Seek(0, SeekOrigin.Begin);
                byte[] buffer = ms.GetBuffer();
                if (buffer.Length != length)
                    buffer = ms.ToArray();
                return buffer;
            }
        }

19 View Source File : IrdTests.cs
License : MIT License
Project Creator : 13xforever

private static MemoryStream GetDecompressHeader(Ird ird)
        {
            var decompressedStream = new MemoryStream();
            using (var compressedStream = new MemoryStream(ird.Header, false))
            using (var gzip = new GZipStream(compressedStream, CompressionMode.Decompress))
                gzip.CopyTo(decompressedStream);
            decompressedStream.Seek(0, SeekOrigin.Begin);
            return decompressedStream;
        }

19 View Source File : SevenZipHelper.cs
License : MIT License
Project Creator : 91Act

public static byte[] Decompress(byte[] inputBytes)
        {
            MemoryStream newInStream = new MemoryStream(inputBytes);

            Decoder decoder = new Decoder();

            newInStream.Seek(0, 0);
            MemoryStream newOutStream = new MemoryStream();

            byte[] properties2 = new byte[5];
            if (newInStream.Read(properties2, 0, 5) != 5)
                throw (new Exception("input .lzma is too short"));
            long outSize = 0;
            for (int i = 0; i < 8; i++)
            {
                int v = newInStream.ReadByte();
                if (v < 0)
                    throw (new Exception("Can't Read 1"));
                outSize |= ((long)(byte)v) << (8 * i);
            }
            decoder.SetDecoderProperties(properties2);

            long compressedSize = newInStream.Length - newInStream.Position;
            decoder.Code(newInStream, newOutStream, compressedSize, outSize, null);

            byte[] b = newOutStream.ToArray();

            return b;
        }

19 View Source File : MemoryIterator.cs
License : Apache License 2.0
Project Creator : aequabit

public bool Write<TSource>(long offset, SeekOrigin origin, TSource data) where TSource: struct
        {
            try
            {
                this._base.Seek(offset, origin);
                byte[] buffer = null;
                if (!this._ubuffer.Translate<TSource>(data, out buffer))
                {
                    throw this._ubuffer.GetLastError();
                }
                this._base.Write(buffer, 0, buffer.Length);
                return true;
            }
            catch (Exception exception)
            {
                return this.SetLastError(exception);
            }
        }

See More Examples