System.IO.Stream.CopyTo(System.IO.Stream)

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

1417 Examples 7

19 View Source File : EdisFace.cs
License : MIT License
Project Creator : 0ffffffffh

private bool ReplyWithFile(HttpListenerContext ctx, string fileName)
        {
            Stream fs;

            if (!File.Exists(fileName))
                return false;

            try
            {
                fs = File.OpenRead(fileName);
            }
            catch(Exception e)
            {
                Log.Error("{0} - {1}", fileName, e.Message);
                return false;
            }

            ctx.Response.ContentLength64 = fs.Length;
            ctx.Response.StatusCode = 200;

            ctx.Response.ContentEncoding = Encoding.ASCII;
            ctx.Response.ContentType = MimeTypeFromExt(Path.GetExtension(fileName));

            fs.CopyTo(ctx.Response.OutputStream);

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

            return true;
        }

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

private void InsertFileRaw(string path, Stream stream) {
            lock (GlobalLock) {
                string? dir = Path.GetDirectoryName(path);
                if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                if (File.Exists(path))
                    File.Delete(path);
                Stream target = File.OpenWrite(path);
                stream.CopyTo(target);
            }
        }

19 View Source File : Protocol16SerializerTest.cs
License : MIT License
Project Creator : 0blu

private void ToString(Stream s)
        {
            MemoryStream ms = new MemoryStream();
            s.Position = 0;
            s.CopyTo(ms);
            string d = "";
            for (int i = 0; i < ms.Length; i++)
            {
                d += "0x" + ms.GetBuffer()[i].ToString("X2") + ", ";
            }
            Console.WriteLine(d);
        }

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 : CelesteNetEmojiComponent.cs
License : MIT License
Project Creator : 0x0ade

public void Handle(CelesteNetConnection con, DataNetEmoji netemoji) {
            Logger.Log(LogLevel.VVV, "netemoji", $"Received {netemoji.ID}");

            string dir = Path.Combine(Path.GetTempPath(), "CelesteNetClientEmojiCache");
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            string path = Path.Combine(dir, $"{netemoji.ID}-{netemoji.GetHashCode():X8}.png");
            using (FileStream fs = File.OpenWrite(path))
            using (MemoryStream ms = new(netemoji.Data))
                ms.CopyTo(fs);

            RunOnMainThread(() => {
                Logger.Log(LogLevel.VVV, "netemoji", $"Registering {netemoji.ID}");

                bool registered = false;

                try {
                    VirtualTexture vt = VirtualContent.CreateTexture(path);
                    MTexture mt = new(vt);
                    if (vt.Texture_Safe == null) // Needed to trigger lazy loading.
                        throw new Exception($"Couldn't load emoji {netemoji.ID}");

                    Registered.Add(netemoji.ID);
                    RegisteredFiles.Add(path);
                    Emoji.Register(netemoji.ID, mt);
                    Emoji.Fill(CelesteNetClientFont.Font);
                    registered = true;

                } finally {
                    if (!registered)
                        File.Delete(path);
                }
            });
        }

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 : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen

static void Main(string[] args)
        {
            AppDomain.CurrentDomain.replacedemblyResolve += (sender, argtwo) => {
                replacedembly thisreplacedembly = replacedembly.GetEntryreplacedembly();
                String resourceName = string.Format("SharpRDP.{0}.dll.bin",
                    new replacedemblyName(argtwo.Name).Name);
                var replacedembly = replacedembly.GetExecutingreplacedembly();
                using (var rs = replacedembly.GetManifestResourceStream(resourceName))
                using (var zs = new DeflateStream(rs, CompressionMode.Decompress))
                using (var ms = new MemoryStream())
                {
                    zs.CopyTo(ms);
                    return replacedembly.Load(ms.ToArray());
                }
            };

            var arguments = new Dictionary<string, string>();
            foreach (string argument in args)
            {
                int idx = argument.IndexOf('=');
                if (idx > 0)
                    arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
            }

            string username = string.Empty;
            string domain = string.Empty;
            string preplacedword = string.Empty;
            string command = string.Empty;
            string execElevated = string.Empty;
            string execw = "";
            bool connectdrive = false;
            bool takeover = false;
            bool nla = false;
            
            if (arguments.ContainsKey("username"))
            {
                if (!arguments.ContainsKey("preplacedword"))
                {
                    Console.WriteLine("[X] Error: A preplacedword is required");
                    return;
                }
                else
                {
                    if (arguments["username"].Contains("\\"))
                    {
                        string[] tmp = arguments["username"].Split('\\');
                        domain = tmp[0];
                        username = tmp[1];
                    }
                    else
                    {
                        domain = ".";
                        username = arguments["username"];
                    }
                    preplacedword = arguments["preplacedword"];
                }
            }

            if (arguments.ContainsKey("preplacedword") && !arguments.ContainsKey("username"))
            {
                Console.WriteLine("[X] Error: A username is required");
                return;
            }
            if ((arguments.ContainsKey("computername")) && (arguments.ContainsKey("command")))
            {
                Client rdpconn = new Client();
                command = arguments["command"];
                if (arguments.ContainsKey("exec"))
                {
                    if (arguments["exec"].ToLower() == "cmd")
                    {
                        execw = "cmd";
                    }
                    else if (arguments["exec"].ToLower() == "powershell" || arguments["exec"].ToLower() == "ps")
                    {
                        execw = "powershell";
                    }
                }
                if (arguments.ContainsKey("elevated"))
                {
                    if(arguments["elevated"].ToLower() == "true" || arguments["elevated"].ToLower() == "win+r" || arguments["elevated"].ToLower() == "winr")
                    {
                        execElevated = "winr";
                    }
                    else if(arguments["elevated"].ToLower() == "taskmgr" || arguments["elevated"].ToLower() == "taskmanager")
                    {
                        execElevated = "taskmgr";
                    }
                    else
                    {
                        execElevated = string.Empty;
                    }
                }
                if (arguments.ContainsKey("connectdrive"))
                {
                    if(arguments["connectdrive"].ToLower() == "true")
                    {
                        connectdrive = true;
                    }
                }
                if (arguments.ContainsKey("takeover"))
                {
                    if (arguments["takeover"].ToLower() == "true")
                    {
                        takeover = true;
                    }
                }
                if (arguments.ContainsKey("nla"))
                {
                    if (arguments["nla"].ToLower() == "true")
                    {
                        nla = true;
                    }
                }
                string[] computerNames = arguments["computername"].Split(',');
                foreach (string server in computerNames)
                {
                    rdpconn.CreateRdpConnection(server, username, domain, preplacedword, command, execw, execElevated, connectdrive, takeover, nla);
                }
            }
            else
            {
                HowTo();
                return;
            }

        }

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

public static Ird Parse(byte[] content)
        {
            if (content == null)
                throw new ArgumentNullException(nameof(content));

            if (content.Length < 200)
                throw new ArgumentException("Data is too small to be a valid IRD structure", nameof(content));

            if (BitConverter.ToInt32(content, 0) != Ird.Magic)
                using (var compressedStream = new MemoryStream(content, false))
                using (var gzip = new GZipStream(compressedStream, CompressionMode.Decompress))
                using (var decompressedStream = new MemoryStream())
                {
                    gzip.CopyTo(decompressedStream);
                    content = decompressedStream.ToArray();
                }
            if (BitConverter.ToInt32(content, 0) != Ird.Magic)
                throw new FormatException("Not a valid IRD file");

            var result = new Ird();
            using (var stream = new MemoryStream(content, false))
            using (var reader = new BinaryReader(stream, Encoding.UTF8))
            {
                reader.ReadInt32(); // magic
                result.Version = reader.ReadByte();
                result.ProductCode = Encoding.ASCII.GetString(reader.ReadBytes(9));
                result.replacedleLength = reader.ReadByte();
                result.replacedle = Encoding.UTF8.GetString(reader.ReadBytes(result.replacedleLength));
                result.UpdateVersion = Encoding.ASCII.GetString(reader.ReadBytes(4)).Trim();
                result.GameVersion = Encoding.ASCII.GetString(reader.ReadBytes(5)).Trim();
                result.AppVersion = Encoding.ASCII.GetString(reader.ReadBytes(5)).Trim();
                if (result.Version == 7)
                    result.Id = reader.ReadInt32();
                result.HeaderLength = reader.ReadInt32();
                result.Header = reader.ReadBytes(result.HeaderLength);
                result.FooterLength = reader.ReadInt32();
                result.Footer = reader.ReadBytes(result.FooterLength);
                result.RegionCount = reader.ReadByte();
                result.RegionMd5Checksums = new List<byte[]>(result.RegionCount);
                for (var i = 0; i < result.RegionCount; i++)
                    result.RegionMd5Checksums.Add(reader.ReadBytes(16));
                result.FileCount = reader.ReadInt32();
                result.Files = new List<IrdFile>(result.FileCount);
                for (var i = 0; i < result.FileCount; i++)
                {
                    var file = new IrdFile();
                    file.Offset = reader.ReadInt64();
                    file.Md5Checksum = reader.ReadBytes(16);
                    result.Files.Add(file);
                }
                result.Unknown = reader.ReadInt32();
                if (result.Version == 9)
                    result.Pic = reader.ReadBytes(115);
                result.Data1 = reader.ReadBytes(16);
                result.Data2 = reader.ReadBytes(16);
                if (result.Version < 9)
                    result.Pic = reader.ReadBytes(115);
                result.Uid = reader.ReadInt32();
                var dataLength = reader.BaseStream.Position;
                result.Crc32 = reader.ReadUInt32();

                var crc32 = Crc32Algorithm.Compute(content, 0, (int)dataLength);
                if (result.Crc32 != crc32)
                    throw new InvalidDataException($"Corrupted IRD data, expected {result.Crc32:x8}, but was {crc32:x8}");
            }
            return result;
        }

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 : 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 : RedisIO.cs
License : MIT License
Project Creator : 2881099

public void Write(Stream stream)
        {
            lock (_streamLock)
            {
                stream.CopyTo(Stream);
                Stream.Flush();
            }
        }

19 View Source File : DefaultRedisSocket.cs
License : MIT License
Project Creator : 2881099

public void Write(CommandPacket cmd)
        {
            if (IsConnected == false) Connect();
            using (var ms = new MemoryStream()) //Writing data directly to will be very slow
            {
                new RespHelper.Resp3Writer(ms, Encoding, Protocol).WriteCommand(cmd);
                ms.Position = 0;
                ms.CopyTo(Stream);
                ms.Close();
            }
            switch (cmd._command)
            {
                case "CLIENT":
                    switch (cmd._subcommand)
                    {
                        case "REPLY":
                            var type = cmd._input.LastOrDefault().ConvertTo<ClientReplyType>();
                            if (type != ClientReply) ClientReply = type;
                            break;
                        case "ID":
                            cmd.OnData(rt =>
                            {
                                ClientId = rt.ThrowOrValue<long>();
                            });
                            break;
                    }
                    break;
                case "SELECT":
                    var dbidx = cmd._input.LastOrDefault()?.ConvertTo<int?>();
                    if (dbidx != null) Database = dbidx.Value;
                    break;
            }
            cmd.WriteTarget = $"{this.Host}/{this.Database}";
        }

19 View Source File : StaticFiles.cs
License : MIT License
Project Creator : 2881099

public static IApplicationBuilder UseFreeAdminLteStaticFiles(this IApplicationBuilder app, string requestPathBase) {
			if (_isStaticFiles == false) {
				lock (_isStaticFilesLock) {
					if (_isStaticFiles == false) {
						var curPath = AppDomain.CurrentDomain.BaseDirectory;
						var zipPath = $"{curPath}/{Guid.NewGuid()}.zip";
						using (var zip = WwwrootStream()) {
							using (var fs = File.Open(zipPath, FileMode.OpenOrCreate)) {
								zip.CopyTo(fs);
								fs.Close();
							}
							zip.Close();
						}
						var wwwrootPath = Path.Combine(curPath, "FreeSql.AdminLTE.wwwroot");
						if (Directory.Exists(wwwrootPath)) Directory.Delete(wwwrootPath, true);
						try {
							System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, wwwrootPath, Encoding.UTF8);
						} catch (Exception ex) {
							throw new Exception($"UseFreeAdminLtePreview 错误,资源文件解压失败:{ex.Message}", ex);
						} finally {
							File.Delete(zipPath);
						}

						app.UseStaticFiles(new StaticFileOptions {
							RequestPath = requestPathBase.TrimEnd('/'),
							FileProvider = new PhysicalFileProvider(wwwrootPath)
						});

						_isStaticFiles = true;
					}
				}
			}

			return app;
		}

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

public static string UnGzip(byte[] buf)
        {
            MemoryStream sb = new MemoryStream();
            using (GZipStream input = new GZipStream(new MemoryStream(buf),
            CompressionMode.Decompress,
            false))
            {
                input.CopyTo(sb);
            }
            return Encoding.UTF8.GetString(sb.ToArray());
        }

19 View Source File : BankIdMissingQrCodeGenerator.cs
License : MIT License
Project Creator : ActiveLogin

private string ConvertToBase64(Stream stream)
        {
            byte[] bytes;

            using (var memoryStream = new MemoryStream())
            {
                stream.CopyTo(memoryStream);
                bytes = memoryStream.ToArray();
            }

            return Convert.ToBase64String(bytes);
        }

19 View Source File : AssemblyExtensions.cs
License : MIT License
Project Creator : adamfisher

public static byte[] GetEmbeddedResourceBytes(this replacedembly replacedembly, string resourceFileName)
        {
            var stream = GetEmbeddedResourceStream(replacedembly, resourceFileName);

            using (var memoryStream = new MemoryStream())
            {
                stream.CopyTo(memoryStream);
                return memoryStream.ToArray();
            }
        }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : Adoxio

public static string SaveFile(this ClientContext context, Stream file, Folder folder, string filename, bool overwrite = false)
		{
			var url = folder.ServerRelativeUrl + "/" + filename;

			// SaveBinaryDirect does not work on Online since it creates its own WebRequest separate from the ClientContext
			// Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, url, file, overwrite);

			if (context.ServerVersion.Major == 14) // SharePoint 2010
			{
				using (var ms = new MemoryStream())
				{
					file.CopyTo(ms);
					var content = ms.ToArray();

					var fci = new FileCreationInformation { Url = url, Overwrite = overwrite, Content = content };
					folder.Files.Add(fci);

					context.ExecuteQuery();
				}
			}
			else
			{
				using (file)
				{
					var fci = new FileCreationInformation { Url = url, Overwrite = overwrite, ContentStream = file };

					folder.Files.Add(fci);

					context.ExecuteQuery();
				}
			}

			return url;
		}

19 View Source File : ChatAuthController.cs
License : MIT License
Project Creator : Adoxio

private static string EncodeState(string state)
		{
			var bytes = Encoding.UTF8.GetBytes(state);
			using (var input = new MemoryStream(bytes))
			using (var output = new MemoryStream())
			{
				using (var zip = new GZipStream(output, CompressionMode.Compress))
				{
					input.CopyTo(zip);
				}

				return Base64UrlEncoder.Encode(output.ToArray());
			}
		}

19 View Source File : ChatAuthController.cs
License : MIT License
Project Creator : Adoxio

private static string DecodeState(string encodedState)
		{
			var bytes = Base64UrlEncoder.DecodeBytes(encodedState);
			using (var input = new MemoryStream(bytes))
			using (var output = new MemoryStream())
			{
				using (var zip = new GZipStream(input, CompressionMode.Decompress))
				{
					zip.CopyTo(output);
				}

				return Encoding.UTF8.GetString(output.ToArray());
			}
		}

19 View Source File : SimpleAudioPlayerImplementation.cs
License : MIT License
Project Creator : adrianstevens

public bool Load(Stream audioStream)
        {
            player.Reset();

            DeleteFile(path);

            //cache to the file system
            path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), $"cache{index++}.wav");
            var fileStream = File.Create(path);
            audioStream.CopyTo(fileStream);
            fileStream.Close();

            try
            {
                player.SetDataSource(path);
            }
            catch
            {
                try
                {
                    var context = Android.App.Application.Context;
                    player?.SetDataSource(context, Uri.Parse(Uri.Encode(path)));
                }
                catch
                {
                    return false;
                }
            }

            return PreparePlayer();
        }

19 View Source File : SimpleAudioPlayerImplementation.cs
License : MIT License
Project Creator : adrianstevens

public bool Load(Stream audioStream)
        {
            DeletePlayer();

            player = GetPlayer();

            if (player != null)
            {
                var fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), $"{++index}.wav");
                using (var fileStream = File.OpenWrite(fileName)) audioStream.CopyTo(fileStream);

                player.Open(new Uri(fileName));
                player.MediaEnded += OnPlaybackEnded;
            }

            return player != null && player.Source != null;
        }

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

public object[] Flush()
        {
            _buffer.Position = 0;
            _buffer.CopyTo(_destination);

            object[] results = new object[_parsers.Count];
            for (int i = 0; i < results.Length; i++)
                results[i] = _parsers.Dequeue()();
            _buffer.SetLength(0);
            Active = false;
            return results;
        }

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

private static bool ExtractManifestResource(string resourceName, string outputPath)
		{
			if (File.Exists(outputPath))
			{
				// This is necessary to prevent access conflicts if multiple processes are run from the
				// same location. The naming scheme implemented in UnmanagedLibrary should ensure that
				// the correct version is always used.
				return true;
			}

			Stream resourceStream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream(resourceName);

			if (resourceStream == null)
			{
				// No manifest resources were compiled into the current replacedembly. This is likely a 'manual
				// deployment' situation, so do not throw an exception at this point and allow all deployment
				// paths to be searched.
				return false;
			}

			try
			{
				using (FileStream fileStream = File.Create(outputPath))
				{
					resourceStream.CopyTo(fileStream);
				}
			}
			catch (UnauthorizedAccessException)
			{
				// Caller does not have write permission for the current file
				return false;
			}

			return true;
		}

19 View Source File : Program.cs
License : The Unlicense
Project Creator : AigioL

static void Main(string[] args)
        {
            TryMain();
            void TryMain()
            {
                try
                {
                    Main();
                }
                catch (Exception ex)
                {
                    var index = byte.MinValue;
                    while (ex != null)
                    {
                        if (index++ > sbyte.MaxValue) break;
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.StackTrace);
                        ex = ex.InnerException;
                    }
                }
                Console.ReadLine();
            }
            void Main()
            {
                // ReSharper disable PossibleNullReferenceException
                var entryreplacedembly = replacedembly.GetEntryreplacedembly();
                var replacedle = entryreplacedembly.FullName.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
                // ReSharper disable once replacedignNullToNotNullAttribute
                if (!replacedle.IsNullOrWhiteSpace()) Console.replacedle = replacedle;
                var rootPath = Path.GetDirectoryName(entryreplacedembly.Location);
                if (rootPath == null) throw new ArgumentNullException(nameof(rootPath));
                var sofilepath = args?.FirstOrDefault(x => x != null && File.Exists(x) && Path.GetExtension(x).Equals(GetSoFileExtension(), StringComparison.OrdinalIgnoreCase));
                if (sofilepath == null)
                {
                    var sofilepaths = Directory.GetFiles(rootPath).Where(x => Path.GetExtension(x).Equals(GetSoFileExtension(), StringComparison.OrdinalIgnoreCase)).ToArray();
                    sofilepath =
                       sofilepaths.FirstOrDefault(x => Path.GetFileName(x).Equals(GetSoDefaultFileName(), StringComparison.OrdinalIgnoreCase)) ??
                       sofilepaths.FirstOrDefault();
                }
                if (sofilepath == null) ReadLineAndExit("Can not find the .so file.");
                // ReSharper disable once replacedignNullToNotNullAttribute
                var bytes = File.ReadAllBytes(sofilepath);
                var elf = Elf.FromFile(sofilepath);
                var rodata = elf.Header.SectionHeaders.FirstOrDefault(x => x.Name.Equals(".rodata"));
                if (rodata == null) ReadLineAndExit(".rodata not found.");
                var packedFiles = new List<string>();
                var addr = (uint)rodata.Addr;
                while (true)
                {
                    //up to 16 bytes of alignment
                    uint i;
                    for (i = 0; i < 16; i++)
                        if (bytes[addr + i] != 0)
                            break;

                    if (i == 16)
                        break; //We found all the files
                    addr += i;

                    var name = GetString(bytes, addr);
                    if (name.IsNullOrWhiteSpace())
                        break;

                    //We only care about dlls
                    if (!name.EndsWith(".dll"))
                        break;

                    packedFiles.Add(name);
                    addr += (uint)name.Length + 1u;
                }
                var data = elf.Header.SectionHeaders.FirstOrDefault(x => x.Name.Equals(".data"));
                if (data == null) ReadLineAndExit(".data not found.");
                int ixGzip = 0;
                addr = (uint)data.Offset;
                var output = Path.Combine(rootPath, "replacedemblies");
                if (!Directory.Exists(output)) Directory.CreateDirectory(output);
                Console.WriteLine($"output:{output}");
                foreach (var item in packedFiles)
                {
                    ixGzip = findNextGZIPIndex(bytes, ixGzip);
                    if (ixGzip > 0)
                    {
                        var ptr = ixGzip;
                        var length = GetBigEndianUInt32(bytes, addr + 8);
                        var compressedbytes = new byte[length];
                        if (ptr + length <= bytes.LongLength)
                        {
                            Array.Copy(bytes, ptr, compressedbytes, 0, length);
                            try
                            {
                                var decompbytes = Decompress(compressedbytes);
                                var path = Path.Combine(output, item);
                                File.WriteAllBytes(path, decompbytes);
                                Console.WriteLine($"file:{item}");
                                addr += 0x10;
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine($"Failed to decompress file: {item} {e.Message}.");
                            }
                        }
                    }
                }
                TryOpenDir(output);
                // ReSharper restore PossibleNullReferenceException
            }
            void ReadLineAndExit(string writeLine = null)
            {
                if (writeLine != null) Console.WriteLine(writeLine);
                Console.ReadLine();
                Environment.Exit(0);
            }
            string GetSoFileExtension() => ".so";
            string GetSoDefaultFileName() => "libmonodroid_bundle_app" + GetSoFileExtension();
            string GetString(byte[] bytes, uint address)
            {
                int maxLength = 255;
                for (int i = (int)address; i < address + maxLength; i++)
                {
                    if (bytes[i] == 0)
                    {
                        maxLength = i - (int)address;
                        break;
                    }
                }
                var buffer = new byte[maxLength];
                Array.Copy(bytes, address, buffer, 0, maxLength);
                return Encoding.ASCII.GetString(buffer);
            }
            int findNextGZIPIndex(byte[] bytes, int ixGzip)
            {
                for (var j = ixGzip + 2; j < bytes.Length; j++)
                {
                    if (bytes[j - 1] == 0x1f && bytes[j] == 0x8b)
                    {
                        ixGzip = j - 1;
                        return ixGzip;
                    }
                }
                return 0;
            }
            byte[] Decompress(byte[] data)
            {
                using (var compressedStream = new MemoryStream(data))
                using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
                using (var resultStream = new MemoryStream())
                {
                    zipStream.CopyTo(resultStream);
                    return resultStream.ToArray();
                }
            }
            uint GetBigEndianUInt32(byte[] bytes, uint address)
            {
                var byte1 = (uint)bytes[(int)address + 3] << 24;
                var byte2 = (uint)bytes[(int)address + 2] << 16;
                var byte3 = (uint)bytes[(int)address + 1] << 8;
                var byte4 = bytes[(int)address];
                return byte1 + byte2 + byte3 + byte4;
            }
            void TryOpenDir(string dirpath)
            {
                try
                {
                    Process.Start(dirpath);
                }
                catch
                {
                    // ignored
                }
            }
        }

19 View Source File : PayloadDecompressor.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public bool TryDecompress(ArraySegment<byte> compressed, MemoryStream decompressed)
        {
            var zlib = this.CompressionLevel == GatewayCompressionLevel.Stream
                ? this.DecompressorStream
                : new DeflateStream(this.CompressedStream, CompressionMode.Decompress, true);

            if (compressed.Array[0] == ZlibPrefix)
                this.CompressedStream.Write(compressed.Array, compressed.Offset + 2, compressed.Count - 2);
            else
                this.CompressedStream.Write(compressed.Array, compressed.Offset, compressed.Count);

            this.CompressedStream.Flush();
            this.CompressedStream.Position = 0;

            var cspan = compressed.replacedpan();
            var suffix = BinaryPrimitives.ReadUInt32BigEndian(cspan.Slice(cspan.Length - 4));
            if (this.CompressionLevel == GatewayCompressionLevel.Stream && suffix != ZlibFlush)
            {
                if (this.CompressionLevel == GatewayCompressionLevel.Payload)
                    zlib.Dispose();

                return false;
            }

            try
            {
                zlib.CopyTo(decompressed);
                return true;
            }
            catch { return false; }
            finally
            {
                this.CompressedStream.Position = 0;
                this.CompressedStream.SetLength(0);

                if (this.CompressionLevel == GatewayCompressionLevel.Payload)
                    zlib.Dispose();
            }
        }

19 View Source File : CustomScanner.cs
License : Apache License 2.0
Project Creator : airbus-cert

public virtual List<ScanResult> ScanStream(
            Stream stream,
            ExternalVariables externalVariables)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                stream.CopyTo(ms);
                byte[] buffer = ms.ToArray();

                return ScanMemory(ref buffer, externalVariables, YR_SCAN_FLAGS.None);
            }
        }

19 View Source File : Scanner.cs
License : Apache License 2.0
Project Creator : airbus-cert

public virtual List<ScanResult> ScanStream(
            Stream stream,
            CompiledRules rules)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                stream.CopyTo(ms);
                byte[] buffer = ms.ToArray();

                return ScanMemory(ref buffer, rules, YR_SCAN_FLAGS.None);
            }
        }

19 View Source File : FileSystemStorageService.cs
License : MIT License
Project Creator : akasarto

public virtual void WriteStream(string blobName, Stream blobStream)
		{
			blobName = blobName ?? throw new ArgumentNullException(nameof(blobName), nameof(FileSystemStorageService));
			blobStream = blobStream ?? throw new ArgumentNullException(nameof(blobStream), nameof(FileSystemStorageService));

			var fileInfo = GetFileInfo(blobName);

			if (!fileInfo.Directory.Exists)
			{
				fileInfo.Directory.Create();
			}

			using (blobStream)
			{
				using (var fStream = fileInfo.OpenWrite())
				{
					blobStream.CopyTo(fStream);
				}
			}
		}

19 View Source File : GzipUtility.cs
License : MIT License
Project Creator : AlenToma

public static byte[] Decompress(byte[] data)
        {
            using (var compressedStream = new MemoryStream(data))
            using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
            using (var resultStream = new MemoryStream())
            {
                zipStream.CopyTo(resultStream);
                return resultStream.ToArray();
            }
        }

19 View Source File : BitStream.cs
License : MIT License
Project Creator : Alexander-Scott

public byte[] GetStreamData()
        {
            stream.Seek(0, SeekOrigin.Begin);
            MemoryStream s = new MemoryStream();
            stream.CopyTo(s);
            Seek(offset, bit);
            return s.ToArray();
        }

19 View Source File : BitStream.cs
License : MIT License
Project Creator : Alexander-Scott

public void CopyStreamTo(Stream stream)
        {
            Seek(0, 0);
            stream.SetLength(this.stream.Length);
            this.stream.CopyTo(stream);
        }

19 View Source File : BitStream.cs
License : MIT License
Project Creator : Alexander-Scott

public void CopyStreamTo(BitStream stream)
        {
            Seek(0, 0);
            stream.ChangeLength(this.stream.Length);
            this.stream.CopyTo(stream.stream);
            stream.Seek(0, 0);
        }

19 View Source File : BitStream.cs
License : MIT License
Project Creator : Alexander-Scott

public void CutStream(long offset, long length)
        {
            byte[] data = GetStreamData();
            byte[] buffer = new byte[length];
            Array.Copy(data, offset, buffer, 0, length);
            this.stream = new MemoryStream();
            MemoryStream m = new MemoryStream(buffer);
            this.stream = new MemoryStream();
            m.CopyTo(this.stream);
            this.offset = 0;
            bit = 0;
        }

19 View Source File : SettingPresetStore.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick

private void buttonStore_Click(object sender, EventArgs e)
    {
      try
      {
        FileInfo f = new FileInfo(@".//Presets//" + textBoxFileName.Text + ".xml");
        if (f.Exists)
        {
          if (MessageBox.Show("Preset with this name already exists.\nOverwrite?", "Preset already exists",
              MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
            return;
        }
        toStore.Description = textBoxDescription.Text;
        // first try to write it into a memory stream to see if Save() finishes correctly
        // only if it does, delete the previous file (if there was one) and write into it
        MemoryStream ms = new MemoryStream();
        toStore.Serialize().Save(ms);
        if (f.Exists)
          f.Delete();
        FileStream fs = f.OpenWrite();
        ms.Position = 0;
        ms.CopyTo(fs);
        ms.Close();
        fs.Close();
        chosenName = textBoxFileName.Text;
        DialogResult = DialogResult.OK;
        Close();
      }
      catch (Exception exc)
      {
        MessageBox.Show("Saving preset to a file failed (make sure the name is a valid name for a file):"
            + Environment.NewLine + Environment.NewLine + exc.Message + Environment.NewLine,
            "Storing preset failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }

19 View Source File : AssemblyUtils.cs
License : MIT License
Project Creator : AlexanderPro

public static void ExtractFileFromreplacedembly(string resourceName, string path)
        {
            var currentreplacedembly = replacedembly.GetExecutingreplacedembly();
            var outputFileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            var resouceStream = currentreplacedembly.GetManifestResourceStream(resourceName);
            resouceStream.CopyTo(outputFileStream);
            resouceStream.Close();
            outputFileStream.Close();
        }

19 View Source File : ViewImageControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private void SaveImageAction()
        {
            var imageUrlWithoutLongId = this.ImageUrl.Substring(0, this.ImageUrl.LastIndexOf('.'));
            var extension = Path.GetExtension(imageUrlWithoutLongId);

            var fileDialogService = Ioc.Default.GetService<IFileDialogService>();
            var filters = new List<FileFilter>
            {
                new FileFilter() { Name = "Image", Extensions = { extension } },
            };

            var filename = fileDialogService.ShowSaveFileDialog("Save Attachment", filters);
            if (!string.IsNullOrEmpty(filename))
            {
                using (var fs = File.OpenWrite(filename))
                {
                    this.ImageStream.Seek(0, SeekOrigin.Begin);
                    this.ImageStream.CopyTo(fs);
                }
            }
        }

19 View Source File : ViewImageControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private void CopyImageAction()
        {
            var clipboardService = Ioc.Default.GetService<IClipboardService>();

            var rawData = new MemoryStream();
            this.ImageStream.Seek(0, SeekOrigin.Begin);
            this.ImageStream.CopyTo(rawData);

            clipboardService.CopyImage(new Core.Controls.Media.GenericImageSource(rawData.ToArray()));
        }

19 View Source File : TileMapAnnotation.cs
License : MIT License
Project Creator : AlexGyver

private OxyImage Download(string uri)
        {
            OxyImage img = null;
            var mre = new ManualResetEvent(false);
            var request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = "GET";
            request.BeginGetResponse(
               r =>
               {
                   try
                   {
                       if (request.HaveResponse)
                       {
                           var response = request.EndGetResponse(r);
                           var stream = response.GetResponseStream();

                           var ms = new MemoryStream();
                           stream.CopyTo(ms);
                           var buffer = ms.ToArray();

                           img = new OxyImage(buffer);
                           this.images[uri] = img;
                       }

                   }
                   catch (Exception e)
                   {
                       var ie = e;
                       while (ie != null)
                       {
                           System.Diagnostics.Debug.WriteLine(ie.Message);
                           ie = ie.InnerException;
                       }
                   }
                   finally
                   {
                       mre.Set();                       
                   }
               },
               request);

            mre.WaitOne();
            return img;
        }

19 View Source File : TileMapAnnotation.cs
License : MIT License
Project Creator : AlexGyver

private void DownloadCompleted(string uri, Stream result)
        {
            if (result == null)
            {
                return;
            }

            var ms = new MemoryStream();
            result.CopyTo(ms);
            var buffer = ms.ToArray();

            var img = new OxyImage(buffer);
            this.images[uri] = img;

            lock (this.queue)
            {
                // Clear old items in the queue, new ones will be added when the plot is refreshed
                foreach (var queuedUri in this.queue)
                {
                    // Remove the 'reserved' image
                    this.images.Remove(queuedUri);
                }

                this.queue.Clear();
            }

            this.PlotModel.InvalidatePlot(false);
            if (this.queue.Count > 0)
            {
                this.BeginDownload();
            }
        }

19 View Source File : CompressionUtils.cs
License : Apache License 2.0
Project Creator : AlexWan

public static string Compress(string s)
        {
            var bytes = Encoding.Unicode.GetBytes(s);
            using (var msi = new MemoryStream(bytes))
            using (var mso = new MemoryStream())
            {
                using (var gs = new GZipStream(mso, CompressionMode.Compress))
                {
                    msi.CopyTo(gs);
                }
                return Convert.ToBase64String(mso.ToArray());
            }
        }

19 View Source File : CompressionUtils.cs
License : Apache License 2.0
Project Creator : AlexWan

public static string Decompress(string s)
        {
            var bytes = Convert.FromBase64String(s);
            using (var msi = new MemoryStream(bytes))
            using (var mso = new MemoryStream())
            {
                using (var gs = new GZipStream(msi, CompressionMode.Decompress))
                {
                    gs.CopyTo(mso);
                }
                return Encoding.Unicode.GetString(mso.ToArray());
            }
        }

19 View Source File : PdfImageConverter.cs
License : MIT License
Project Creator : allantargino

private FileInfo ToFile(Stream stream, string fileName)
        {
            string pdfFile = [email protected]"{_tempFolder}\{fileName}";

            using (var fileStream = File.Create(pdfFile))
            {
                stream.Seek(0, SeekOrigin.Begin);
                stream.CopyTo(fileStream);
                stream.Close();
            }

            return new FileInfo(pdfFile);
        }

19 View Source File : GzipDataReader.cs
License : MIT License
Project Creator : aloneguid

private static void Decompress(Stream source, Stream destination)
      {
         if (source == null) throw new ArgumentNullException(nameof(source));
         if (destination == null) throw new ArgumentNullException(nameof(destination));

         using (var decompressor = new GZipStream(source, CompressionMode.Decompress, true))
         {
            decompressor.CopyTo(destination);
            destination.Flush();
         }
      }

19 View Source File : GzipDataWriter.cs
License : MIT License
Project Creator : aloneguid

private static void Compress(Stream source, Stream destination)
      {
         if (source == null) throw new ArgumentNullException(nameof(source));
         if (destination == null) throw new ArgumentNullException(nameof(destination));

         using (var compressor = new GZipStream(destination, CompressionLevel.Optimal, true))
         {
            source.CopyTo(compressor);
            compressor.Flush();
         }
      }

19 View Source File : RunLengthBitPackingHybridValuesWriter.cs
License : MIT License
Project Creator : aloneguid

public static void WriteForwardOnly(BinaryWriter writer, int bitWidth, int[] data, int count)
      {
         //write data to a memory buffer, as we need data length to be written before the data
         using (var ms = new MemoryStream())
         {
            using (var bw = new BinaryWriter(ms, Encoding.UTF8, true))
            {
               //write actual data
               WriteData(bw, data, count, bitWidth);
            }

            //int32 - length of data
            writer.Write((int)ms.Length);

            //actual data
            ms.Position = 0;
            ms.CopyTo(writer.BaseStream); //warning! CopyTo performs .Flush internally
         }
      }

19 View Source File : DataColumnWriter.cs
License : MIT License
Project Creator : aloneguid

private List<PageTag> WriteColumn(DataColumn column,
         Thrift.SchemaElement tse,
         IDataTypeHandler dataTypeHandler,
         int maxRepereplacedionLevel,
         int maxDefinitionLevel)
      {
         var pages = new List<PageTag>();

         /*
          * Page header must preceeed actual data (compressed or not) however it contains both
          * the uncompressed and compressed data size which we don't know! This somehow limits
          * the write efficiency.
          */


         using (var ms = new MemoryStream())
         {
            Thrift.PageHeader dataPageHeader = _footer.CreateDataPage(column.Data.Length);

            //chain streams together so we have real streaming instead of wasting undefraggable LOH memory
            using (GapStream pageStream = DataStreamFactory.CreateWriter(ms, _compressionMethod, _compressionLevel, true))
            {
               using (var writer = new BinaryWriter(pageStream, Encoding.UTF8, true))
               {
                  if (column.RepereplacedionLevels != null)
                  {
                     WriteLevels(writer, column.RepereplacedionLevels, column.RepereplacedionLevels.Length, maxRepereplacedionLevel);
                  }

                  ArrayView data = new ArrayView(column.Data);

                  if (maxDefinitionLevel > 0)
                  {
                     data = column.PackDefinitions(maxDefinitionLevel, out int[] definitionLevels, out int definitionLevelsLength, out int nullCount);

                     //last chance to capture null count as null data is compressed now
                     column.Statistics.NullCount = nullCount;

                     try
                     {
                        WriteLevels(writer, definitionLevels, definitionLevelsLength, maxDefinitionLevel);
                     }
                     finally
                     {
                        if (definitionLevels != null)
                        {
                           ArrayPool<int>.Shared.Return(definitionLevels);
                        }
                     }
                  }
                  else
                  {
                     //no defitions means no nulls
                     column.Statistics.NullCount = 0;
                  }

                  dataTypeHandler.Write(tse, writer, data, column.Statistics);

                  writer.Flush();
               }

               pageStream.Flush();   //extremely important to flush the stream as some compression algorithms don't finish writing
               pageStream.MarkWriteFinished();
               dataPageHeader.Uncompressed_page_size = (int)pageStream.Position;
            }
            dataPageHeader.Compressed_page_size = (int)ms.Position;

            //write the header in
            dataPageHeader.Data_page_header.Statistics = column.Statistics.ToThriftStatistics(dataTypeHandler, _schemaElement);
            int headerSize = _thriftStream.Write(dataPageHeader);
            ms.Position = 0;
            ms.CopyTo(_stream);


            var dataTag = new PageTag
            {
               HeaderMeta = dataPageHeader,
               HeaderSize = headerSize
            };

            pages.Add(dataTag);
         }

         return pages;
      }

19 View Source File : DataStreamFactory.cs
License : MIT License
Project Creator : aloneguid

public static BytesOwner ReadPageData(Stream nakedStream, Thrift.CompressionCodec compressionCodec,
         int compressedLength, int uncompressedLength)
      {
         if (!_codecToCompressionMethod.TryGetValue(compressionCodec, out CompressionMethod compressionMethod))
            throw new NotSupportedException($"reader for compression '{compressionCodec}' is not supported.");

         int totalBytesRead = 0;
         int currentBytesRead = int.MinValue;
         byte[] data = BytesPool.Rent(compressedLength);
         bool dataRented = true;

         // Some storage solutions (like Azure blobs) might require more than one 'Read' action to read the requested length.
         while (totalBytesRead < compressedLength && currentBytesRead != 0)
         {
            currentBytesRead = nakedStream.Read(data, totalBytesRead, compressedLength - totalBytesRead);
            totalBytesRead += currentBytesRead;
         }

         if (totalBytesRead != compressedLength)
         {
            throw new ParquetException($"expected {compressedLength} bytes in source stream but could read only {totalBytesRead}");
         }

         switch (compressionMethod)
         {
            case CompressionMethod.None:
               //nothing to do, original data is the raw data
               break;
            case CompressionMethod.Gzip:
               using (var source = new MemoryStream(data, 0, compressedLength))
               {
                  byte[] unGzData = BytesPool.Rent(uncompressedLength);
                  using (var dest = new MemoryStream(unGzData, 0, uncompressedLength))
                  {
                     using (var gz = new GZipStream(source, CompressionMode.Decompress))
                     {
                        gz.CopyTo(dest);
                     }
                  }
                  BytesPool.Return(data);
                  data = unGzData;
               }
               break;
            case CompressionMethod.Snappy:
               byte[] uncompressed = Snappy.Decode(data.replacedpan(0, compressedLength));
               BytesPool.Return(data);
               data = uncompressed;
               dataRented = false;
               break;
            default:
               throw new NotSupportedException("method: " + compressionMethod);
         }

         return new BytesOwner(data, 0, data.AsMemory(0, uncompressedLength), d => BytesPool.Return(d), dataRented);
      }

19 View Source File : Program.cs
License : MIT License
Project Creator : aloneguid

static void CompressNew(string src, string dest)
      {
         using (FileStream streamDest = F.OpenWrite(dest))
         {
            using (Stream streamSnappy = IronSnappy.Snappy.OpenWriter(streamDest))
            {
               using(FileStream streamSrc = F.OpenRead(src))
               {
                  using(var time = new TimeMeasure())
                  {
                     streamSrc.CopyTo(streamSnappy);

                     TimeSpan duration = time.Elapsed;

                     Console.WriteLine($"new: {src} => {dest}. {duration} {new FileInfo(dest).Length}");
                  }
               }
            }
         }
      }

19 View Source File : ParquetReaderTest.cs
License : MIT License
Project Creator : aloneguid

[Fact]
      public void ParquetReader_OpenFromFile_Close_Stream()
      {
         // copy a file to a temp location
         string tempFile = Path.GetTempFileName();
         using (Stream fr = OpenTestFile("map_simple.parquet"))
         using (FileStream fw = System.IO.File.OpenWrite(tempFile))
         {
            fr.CopyTo(fw);
         }
               
         // open the copy
         using (var reader = ParquetReader.OpenFromFile(tempFile))
         {
            // do nothing
         }
         
         // now try to delete this temp file. If the stream is properly closed, this should succeed
         System.IO.File.Delete(tempFile);
      }

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

public Task<Stream> GetBinaryData(string org, string app, int instanceOwnerId, Guid instanceGuid, Guid dataId)
        {
            string dataPath = GetDataBlobPath(org, app.Split("/")[1], instanceOwnerId, instanceGuid, dataId);

            Stream ms = new MemoryStream();
            using (FileStream file = new FileStream(dataPath, FileMode.Open, FileAccess.Read))
            {
                file.CopyTo(ms);
            }

            return Task.FromResult(ms);
        }

See More Examples