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
19
Source : ByteString.cs
with MIT License
from bluexo
with MIT License
from bluexo
public static ByteString FromStream(Stream stream)
{
ProtoPreconditions.CheckNotNull(stream, "stream");
int capacity = stream.CanSeek ? checked((int) (stream.Length - stream.Position)) : 0;
var memoryStream = new MemoryStream(capacity);
stream.CopyTo(memoryStream);
// Avoid an extra copy if we can.
byte[] bytes = memoryStream.Length == memoryStream.Capacity ? memoryStream.GetBuffer() : memoryStream.ToArray();
return AttachBytes(bytes);
}
19
Source : TEStorageUnit.cs
with MIT License
from blushiemagic
with MIT License
from blushiemagic
public override void NetSend(BinaryWriter trueWriter, bool lightSend)
{
//If the workaround is active, then the enreplacedy isn't being sent via the NetWorkaround packet or is being saved to a world file
if (EditsLoader.MessageTileEnreplacedySyncing)
{
trueWriter.Write((byte)0);
base.NetSend(trueWriter, lightSend);
return;
}
trueWriter.Write((byte)1);
/* Recreate a BinaryWriter writer */
MemoryStream buffer = new MemoryStream(65536);
DeflateStream compressor = new DeflateStream(buffer, CompressionMode.Compress, true);
BufferedStream writerBuffer = new BufferedStream(compressor, 65536);
BinaryWriter writer = new BinaryWriter(writerBuffer);
/* Original code */
base.NetSend(writer, lightSend);
if (netQueue.Count > Capacity / 2 || !lightSend)
{
netQueue.Clear();
netQueue.Enqueue(UnitOperation.FullSync.Create());
}
writer.Write((ushort)netQueue.Count);
while (netQueue.Count > 0)
{
netQueue.Dequeue().Send(writer, this);
}
/* Forces data to be flushed into the compressed buffer */
writerBuffer.Flush(); compressor.Close();
/* Sends the buffer through the network */
trueWriter.Write((ushort)buffer.Length);
trueWriter.Write(buffer.ToArray());
/* Compression stats and debugging code (server side) */
if (false)
{
MemoryStream decompressedBuffer = new MemoryStream(65536);
DeflateStream decompressor = new DeflateStream(buffer, CompressionMode.Decompress, true);
decompressor.CopyTo(decompressedBuffer);
decompressor.Close();
Console.WriteLine("Magic Storage Data Compression Stats: " + decompressedBuffer.Length + " => " + buffer.Length);
decompressor.Dispose(); decompressedBuffer.Dispose();
}
/* Dispose all objects */
writer.Dispose(); writerBuffer.Dispose(); compressor.Dispose(); buffer.Dispose();
}
19
Source : Ext.cs
with MIT License
from bonzaiferroni
with MIT License
from bonzaiferroni
internal static byte [] ToByteArray (this Stream stream)
{
using (var output = new MemoryStream ()) {
stream.Position = 0;
stream.CopyTo (output);
output.Close ();
return output.ToArray ();
}
}
19
Source : Ext.cs
with MIT License
from bonzaiferroni
with MIT License
from bonzaiferroni
internal static void WriteBytes (this Stream stream, byte [] value)
{
using (var src = new MemoryStream (value)) {
src.CopyTo (stream);
}
}
19
Source : Ext.cs
with MIT License
from bonzaiferroni
with MIT License
from bonzaiferroni
private static MemoryStream compress (this Stream stream)
{
var output = new MemoryStream ();
if (stream.Length == 0)
return output;
stream.Position = 0;
using (var ds = new DeflateStream (output, CompressionMode.Compress, true)) {
stream.CopyTo (ds);
ds.Close (); // "BFINAL" set to 1.
output.Position = 0;
return output;
}
}
19
Source : FilePath.cs
with MIT License
from Bphots
with MIT License
from Bphots
public void ReadFromStream([NotNull] Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
stream.Position = 0;
using (FileStream fileStream = Value.OpenWrite())
stream.CopyTo(fileStream);
}
19
Source : StreamHelper.cs
with MIT License
from Braini01
with MIT License
from Braini01
private static MemoryStream MakeBuffer(Stream stream)
{
var ms = new MemoryStream((int)stream.Length);
stream.CopyTo(ms);
ms.Position = 0;
return ms;
}
19
Source : PngByteQRCode.cs
with GNU General Public License v3.0
from BRH-Media
with GNU General Public License v3.0
from BRH-Media
public void WriteScanlines(byte[] scanlines)
{
using (var idatStream = new MemoryStream())
{
Deflate(idatStream, scanlines);
this.WriteChunkStart(IDAT, (int)(idatStream.Length + 6));
// Deflate header.
this.stream.WriteByte(0x78); // 8 Deflate algorithm, 7 max window size
this.stream.WriteByte(0x9C); // Check bits.
// Compressed data.
idatStream.Position = 0;
#if NET35
idatStream.WriteTo(this.stream);
#else
idatStream.CopyTo(this.stream);
#endif
// Deflate checksum.
var adler = Adler32(scanlines, 0, scanlines.Length);
this.WriteIntBigEndian(adler);
this.WriteChunkEnd();
}
}
19
Source : Emulator.cs
with MIT License
from bryanperris
with MIT License
from bryanperris
private Cartridge MountCartridge(String path)
{
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
MemoryStream rom = new MemoryStream();
fs.Position = 0;
fs.CopyTo(rom);
// N64BareMetalreplacedembler replacedembler = new N64BareMetalreplacedembler("foorom");
// replacedembler.AddreplacedemblySource(new replacedemblyStreamSource("test", fs));
// replacedembler.replacedembleCode(true);
// Stream rom = replacedembler.Output;
//rom.Position = 0;
var cart = new Cartridge(rom);
Log.Info("replacedle: {0}", cart.Name);
Log.Info("Filename: {0}", Path.GetFileName(path));
Log.Info("Entry Point: 0x{0:X8}", cart.EntryPoint);
Log.Info("Checksum: 0x{0:X8}{1:X8}", cart.Crc1, cart.Crc2);
var md5 = "Cart IPL3 MD5: 0x";
foreach (Byte b in cart.BootChecksumMD5)
{
md5 += b.ToString("X2");
}
Log.Info(md5);
return cart;
}
}
19
Source : OkexSocketClient.cs
with MIT License
from burakoner
with MIT License
from burakoner
protected static string DecompressData(byte[] byteData)
{
using (var decompressedStream = new MemoryStream())
using (var compressedStream = new MemoryStream(byteData))
using (var deflateStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
{
deflateStream.CopyTo(decompressedStream);
decompressedStream.Position = 0;
using (var streamReader = new StreamReader(decompressedStream))
{
/** /
var response = streamReader.ReadToEnd();
return response;
/**/
return streamReader.ReadToEnd();
}
}
}
19
Source : ExportService.cs
with GNU General Public License v3.0
from bykovme
with GNU General Public License v3.0
from bykovme
public static byte[] GetBytesFromStream(Stream input)
{
using (MemoryStream ms = new MemoryStream()) {
input.CopyTo(ms);
return ms.ToArray();
}
}
19
Source : DataAccessLayer.cs
with GNU General Public License v3.0
from bykovme
with GNU General Public License v3.0
from bykovme
public static void RestoreDemoDatabase()
{
Close();
Stream demoFileStream = NSWRes.GetDemoFileTEMPORARY();
var fileStream = new FileStream(DBFile, FileMode.Create, FileAccess.Write);
demoFileStream.CopyTo(fileStream);
fileStream.Dispose();
demoFileStream.Dispose();
Init(DBFile);
}
19
Source : Resources.cs
with GNU General Public License v3.0
from bykovme
with GNU General Public License v3.0
from bykovme
public static string WriteResFileToTempFolder(string filename) {
Stream fileStreamIn = null;
string tempFile = "";
try {
fileStreamIn = GetStreamFromTestResource(filename);
var tempFolder = Path.GetTempPath();
tempFile = tempFolder + filename;
using (var fileStreamOut = File.Create(tempFile)) {
fileStreamIn.Seek(0, SeekOrigin.Begin);
fileStreamIn.CopyTo(fileStreamOut);
}
} catch(Exception ex) {
tempFile = "";
AppLogs.Log(ex.Message, nameof(WriteResFileToTempFolder), nameof(TestResources));
} finally {
if (fileStreamIn != null) {
fileStreamIn.Close();
}
}
return tempFile;
}
19
Source : BXJGFileMultipartFormDataStreamProvider.cs
with MIT License
from bxjg1987
with MIT License
from bxjg1987
public override async Task ExecutePostProcessingAsync()
{
await base.ExecutePostProcessingAsync(); //填充FormData属性(表单数据)
if (!IsChunk)
return;
//最后几个分片可能同时上了。多个用户可能上传同一个文件,都可能造成并发冲突
//目前这种合并方式是相对好点的
string[] files = Directory.GetFiles(TempDirectory);
if (Chunk != Chunks - 1 || files.Length != Chunks)
return;
var newFileName = CreateFilePath();
FileStream stream = null;
try
{
stream = new FileStream(newFileName, FileMode.CreateNew);
}
catch (IOException ex)
{
if (ex.HResult != -2147024816)
throw;
//Logger.WarnFormat("分片上传文件时创建文件流失败:" + ex.Message);
return;
}
using (stream)
{
var sortedFiles = files.OrderBy(c => int.Parse(Path.GetFileNameWithoutExtension(c)));
await Task.Run(async () =>
{
foreach (var item in sortedFiles)
{
#region MyRegion
//此时可能另一个分片并没有读取完成
for (int i = 0; i < 10000; i++)
{
try
{
using (var fs = System.IO.File.OpenRead(item))
{
fs.CopyTo(stream);
}
break;
}
catch (IOException ex)
{
if (ex.HResult != -2147024864)
throw;
await Task.Delay(2);
}
}
#endregion
}
});
}
var lastCT = FileData.First();
var heders = lastCT.Headers;
base.FileData.Clear();
FileData.Add(new MultipartFileData(heders, newFileName));
Directory.Delete(TempDirectory, true);
IsChunk = false;
}
19
Source : FileController.cs
with GNU General Public License v3.0
from bykovme
with GNU General Public License v3.0
from bykovme
public static string WriteStreamToDoreplacedents(Stream stream, string filename)
{
try {
var ms = new MemoryStream();
stream.CopyTo(ms);
var path = CombinePaths(GetDoreplacedentsPath, filename);
WriteToFile(path, ms);
return path;
} catch {
return null;
}
}
19
Source : IconScreenViewModel.cs
with GNU General Public License v3.0
from bykovme
with GNU General Public License v3.0
from bykovme
byte[] resizeImage(Stream imageStream)
{
if (imageStream != null) {
using (var ms = new System.IO.MemoryStream()) {
imageStream.CopyTo(ms);
var imageBytes = ms.ToArray();
return MediaService.ResizeImage(
imageBytes,
GConsts.RESIZE_ICON_WIDTH,
GConsts.RESIZE_ICON_HEIGHT
);
}
}
return null;
}
19
Source : Http.cs
with GNU General Public License v3.0
from byt3bl33d3r
with GNU General Public License v3.0
from byt3bl33d3r
public static byte[] Post(Uri url, byte[] payload)
{
var wr = WebRequest.Create(url);
wr.Method = "POST";
wr.ContentType = "application/octet-stream";
wr.ContentLength = payload.Length;
var requestStream = wr.GetRequestStream();
requestStream.Write(payload, 0, payload.Length);
requestStream.Close();
var response = wr.GetResponse();
using (var stream = new MemoryStream())
{
response.GetResponseStream()?.CopyTo(stream);
return stream.ToArray();
}
}
19
Source : Resources.cs
with GNU General Public License v3.0
from byt3bl33d3r
with GNU General Public License v3.0
from byt3bl33d3r
public static byte[] GetByName(string resourceName)
{
var query = $"Kaliya.Resources.{resourceName}";
var asm = replacedembly.GetExecutingreplacedembly();
var res = asm.GetManifestResourceNames();
var resQuery =
from name in res
where name == query
select name;
var resName = resQuery.Single();
using (var resourceStream = asm.GetManifestResourceStream(resName))
{
using (var memoryStream = new MemoryStream())
{
resourceStream?.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
}
19
Source : PathOfBuildingService.cs
with MIT License
from C1rdec
with MIT License
from C1rdec
public string Encode(string build)
{
using (var output = new MemoryStream())
{
using (var input = new MemoryStream(Encoding.ASCII.GetBytes(build)))
{
using (var decompressor = new GZipStream(output, CompressionMode.Compress))
{
input.CopyTo(decompressor);
return Convert.ToBase64String(output.ToArray());
}
}
}
}
19
Source : PathOfBuildingService.cs
with MIT License
from C1rdec
with MIT License
from C1rdec
private static string GetXml(string build)
{
if (IsValidXml(build))
{
return build;
}
try
{
using (var output = new MemoryStream())
{
using (var input = new MemoryStream(Convert.FromBase64String(build.Replace("_", "/").Replace("-", "+"))))
{
using (var decompressor = new GZipStream(input, CompressionMode.Decompress))
{
decompressor.CopyTo(output);
return Encoding.UTF8.GetString(output.ToArray());
}
}
}
}
catch
{
return string.Empty;
}
}
19
Source : StreamExtensions.cs
with MIT License
from CacoCode
with MIT License
from CacoCode
[Description("获取字节数组")]
public static byte[] GetAllBytes(this Stream stream)
{
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
19
Source : CakeScriptSerializer.cs
with MIT License
from cake-build
with MIT License
from cake-build
public static byte[] Zip(string str)
{
var bytes = Encoding.UTF8.GetBytes(str);
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(mso, CompressionMode.Compress))
{
msi.CopyTo(gs);
}
return mso.ToArray();
}
}
19
Source : CakeScriptSerializer.cs
with MIT License
from cake-build
with MIT License
from cake-build
public static string Unzip(byte[] bytes)
{
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(msi, CompressionMode.Decompress))
{
gs.CopyTo(mso);
}
return Encoding.UTF8.GetString(mso.ToArray());
}
}
19
Source : IsolatedStorageUtility.cs
with MIT License
from CalciumFramework
with MIT License
from CalciumFramework
public async Task CopyApplicationResourceToIsolatedStorageAsync(
string inResourceName, string outFilename)
{
replacedertArg.IsNotNull(inResourceName, nameof(inResourceName));
replacedertArg.IsNotNull(outFilename, nameof(outFilename));
Uri uri = new Uri(inResourceName, UriKind.Relative);
using (Stream resourceStream = await GetApplicationResourceStreamAsync(uri))//Application.GetResourceStream(uri).Stream)
{
using (IsolatedStorageFile isolatedStorageFile
= IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream outStream
= isolatedStorageFile.CreateFile(outFilename))
{
resourceStream.CopyTo(outStream);
}
}
}
}
19
Source : IsolatedStorageUtility.cs
with MIT License
from CalciumFramework
with MIT License
from CalciumFramework
public async Task CopyApplicationResourcesToIsolatedStorageAsync(
IEnumerable<KeyValuePair<string, string>> sourceToDestinationList)
{
replacedertArg.IsNotNull(sourceToDestinationList, nameof(sourceToDestinationList));
using (IsolatedStorageFile isolatedStorageFile
= IsolatedStorageFile.GetUserStoreForApplication())
{
foreach (var sourceAndDestination in sourceToDestinationList)
{
Uri uri = new Uri(sourceAndDestination.Key, UriKind.Relative);
using (Stream resourceStream = await GetApplicationResourceStreamAsync(uri))//Application.GetResourceStream(uri).Stream)
{
string destination = sourceAndDestination.Value;
if (string.IsNullOrWhiteSpace(destination))
{
throw new ArgumentException($"Key '{sourceAndDestination.Key}' has null pair Value. A destination must be specified.");
}
int separatorIndex = destination.LastIndexOf("/");
if (separatorIndex == destination.Length - 1)
{
throw new InvalidOperationException(
$"Destination '{destination}' should not end with '/'");
}
string directory = null;
if (separatorIndex != -1)
{
directory = destination.Substring(0, separatorIndex);
}
if (!string.IsNullOrWhiteSpace(directory)
&& !isolatedStorageFile.DirectoryExists(directory))
{
isolatedStorageFile.CreateDirectory(directory);
}
// if (isolatedStorageFile.FileExists(destination))
// {
// isolatedStorageFile.DeleteFile(destination);
// }
using (IsolatedStorageFileStream outStream
= isolatedStorageFile.CreateFile(destination))
{
resourceStream.CopyTo(outStream);
}
}
}
}
}
19
Source : PortablePdb.cs
with MIT License
from CatLib
with MIT License
from CatLib
static Stream GetPortablePdbStream (ImageDebugHeaderEntry entry)
{
var compressed_stream = new MemoryStream (entry.Data);
var reader = new BinaryStreamReader (compressed_stream);
reader.ReadInt32 (); // signature
var length = reader.ReadInt32 ();
var decompressed_stream = new MemoryStream (length);
using (var deflate_stream = new DeflateStream (compressed_stream, CompressionMode.Decompress, leaveOpen: true))
deflate_stream.CopyTo (decompressed_stream);
return decompressed_stream;
}
19
Source : PortablePdb.cs
with MIT License
from CatLib
with MIT License
from CatLib
public ImageDebugHeader GetDebugHeader ()
{
writer.Dispose ();
var directory = new ImageDebugDirectory {
Type = ImageDebugType.EmbeddedPortablePdb,
MajorVersion = 0x0100,
MinorVersion = 0x0100,
};
var data = new MemoryStream ();
var w = new BinaryStreamWriter (data);
w.WriteByte (0x4d);
w.WriteByte (0x50);
w.WriteByte (0x44);
w.WriteByte (0x42);
w.WriteInt32 ((int) stream.Length);
stream.Position = 0;
using (var compress_stream = new DeflateStream (data, CompressionMode.Compress, leaveOpen: true))
stream.CopyTo (compress_stream);
directory.SizeOfData = (int) data.Length;
return new ImageDebugHeader (new [] {
writer.GetDebugHeader ().Entries [0],
new ImageDebugHeaderEntry (directory, data.ToArray ())
});
}
19
Source : ModuleDefinition.cs
with MIT License
from CatLib
with MIT License
from CatLib
public static ModuleDefinition ReadModule (string fileName, ReaderParameters parameters)
{
var stream = GetFileStream (fileName, FileMode.Open, parameters.ReadWrite ? FileAccess.ReadWrite : FileAccess.Read, FileShare.Read);
if (parameters.InMemory) {
var memory = new MemoryStream (stream.CanSeek ? (int) stream.Length : 0);
using (stream)
stream.CopyTo (memory);
memory.Position = 0;
stream = memory;
}
try {
return ReadModule (Disposable.Owned (stream), fileName, parameters);
} catch (Exception) {
stream.Dispose ();
throw;
}
}
19
Source : HisDataMemoryBlockCollection3.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public unsafe static void RecordToLog(this IntPtr address, int size, Stream stream)
{
using (System.IO.UnmanagedMemoryStream ums = new UnmanagedMemoryStream((byte*)address, size))
{
ums.CopyTo(stream);
}
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public string GetSecuritySetting(int timeout = 50000)
{
string filename = string.Empty;
var mb = GetBuffer(ApiFunConst.TagInfoRequest, 1 + 9);
mb.Write(ApiFunConst.SyncSecuritySetting);
mb.Write(LoginId);
this.SyncDataEvent.Reset();
SendData(mb);
if (SyncDataEvent.WaitOne(timeout))
{
try
{
if (this.mRealSyncData.WriteIndex - mRealSyncData.ReadIndex > 0)
{
try
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ms.Write(this.mRealSyncData.ReadBytes((int)(this.mRealSyncData.WriteIndex - mRealSyncData.ReadIndex)));
ms.Position = 0;
System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress);
filename = System.IO.Path.GetTempFileName();
var sfile = System.IO.File.Open(filename, System.IO.FileMode.OpenOrCreate);
gzip.CopyTo(sfile);
sfile.Close();
ms.Dispose();
gzip.Dispose();
return filename;
}
catch
{
}
}
}
finally
{
mRealSyncData?.UnlockAndReturn();
mRealSyncData = null;
}
}
return filename;
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public string GetRealdatabase(int timeout = 50000)
{
string filename = string.Empty;
var mb = GetBuffer(ApiFunConst.TagInfoRequest, 1 + 9);
mb.Write(ApiFunConst.SyncRealTagConfig);
mb.Write(LoginId);
this.SyncDataEvent.Reset();
SendData(mb);
if (SyncDataEvent.WaitOne(timeout))
{
try
{
if ((this.mRealSyncData.WriteIndex - mRealSyncData.ReadIndex) > 0)
{
try
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ms.Write(this.mRealSyncData.ReadBytes((int)(this.mRealSyncData.WriteIndex - mRealSyncData.ReadIndex)));
ms.Position = 0;
System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress);
filename = System.IO.Path.GetTempFileName();
var sfile = System.IO.File.Open(filename, System.IO.FileMode.OpenOrCreate);
gzip.CopyTo(sfile);
sfile.Close();
ms.Dispose();
gzip.Dispose();
return filename;
}
catch
{
}
}
}
finally
{
mRealSyncData?.UnlockAndReturn();
mRealSyncData = null;
}
}
return filename;
}
19
Source : CustomCursor.cs
with MIT License
from CefNet
with MIT License
from CefNet
public unsafe static Cursor Create(ref CefCursorInfo cursorInfo)
{
CefSize size = cursorInfo.Size;
if (size.Width > 0 && size.Height > 0 && cursorInfo.Buffer != IntPtr.Zero)
{
try
{
var bufferSize = size.Width * size.Height * 4;
int ICON_HEADER_SIZE = sizeof(ICONDIR);
var stream = new MemoryStream();
{
DpiScale dpi = OffscreenGraphics.DpiScale;
var source = BitmapSource.Create(size.Width, size.Height, dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Bgra32, null, cursorInfo.Buffer, bufferSize, size.Width << 2);
if (stream.Seek(ICON_HEADER_SIZE, SeekOrigin.Begin) != ICON_HEADER_SIZE)
{
stream.Seek(0, SeekOrigin.Begin);
stream.Write(new byte[ICON_HEADER_SIZE], 0, ICON_HEADER_SIZE);
}
var png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(source));
png.Save(stream);
stream.Seek(0, SeekOrigin.Begin);
}
CefPoint hotSpot = cursorInfo.Hotspot;
var icon = new ICONDIR();
icon.IconType = 2;
icon.ImagesCount = 1;
icon.Width = (byte)size.Width;
icon.Height = (byte)size.Height;
icon.HotSpotX = (short)hotSpot.X;
icon.HotSpotY = (short)hotSpot.Y;
icon.BytesInRes = (int)stream.Length - ICON_HEADER_SIZE;
icon.ImageOffset = ICON_HEADER_SIZE;
using (var iconHead = new UnmanagedMemoryStream(icon._data, ICON_HEADER_SIZE))
{
iconHead.CopyTo(stream);
stream.Seek(0, SeekOrigin.Begin);
}
return new Cursor(stream);
}
catch (AccessViolationException) { throw; }
catch { }
}
return Cursors.Arrow;
}
19
Source : PluginController.cs
with MIT License
from chanjunweimy
with MIT License
from chanjunweimy
private FileContentResult LoadFileFromStream(Stream stream, string filename)
{
var memstream = new MemoryStream();
stream.CopyTo(memstream);
var fileBytes = memstream.ToArray();
return LoadFileFromByteArray(filename, fileBytes);
}
19
Source : ADBHelper.cs
with GNU General Public License v3.0
from Charltsing
with GNU General Public License v3.0
from Charltsing
private byte[] RunAdbProcess(string shellcommand)
{
byte[] raw;
using (Process p = new Process())
{
p.StartInfo.FileName = AdbPath; // @"C:\Android\sdk\platform-tools\adb.exe";
p.StartInfo.Arguments = shellcommand;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true; //重定向标准输入
p.StartInfo.RedirectStandardOutput = true; //重定向标准输出
p.StartInfo.RedirectStandardError = true; //重定向错误输出
p.StartInfo.CreateNoWindow = true;
p.Start();
//https://www.cnblogs.com/jackdong/archive/2011/03/31/2000740.html
//OutputData = p.StandardOutput.ReadToEnd(); //这一句执行之后,BaseStream就被读取,无法再读。
MemoryStream OutputStream = new MemoryStream();
p.StandardOutput.BaseStream.CopyTo(OutputStream);
OutputStream.Position = 0;
raw = OutputStream.ToArray();
p.WaitForExit();
p.Close();
}
return raw;
}
19
Source : Worker.cs
with MIT License
from Charterino
with MIT License
from Charterino
public replacedemblyDef DecompressCosturareplacedembly(Stream resource)
{
using (var def = new DeflateStream(resource, CompressionMode.Decompress))
{
var ms = new MemoryStream();
def.CopyTo(ms);
ms.Position = 0;
return replacedemblyDef.Load(ms);
}
}
19
Source : ResourceHelper.cs
with Apache License 2.0
from Chem4Word
with Apache License 2.0
from Chem4Word
public static void WriteResource(replacedembly replacedembly, string resourceName, string destPath)
{
Stream stream = GetBinaryResource(replacedembly, resourceName);
using (var fileStream = new FileStream(destPath, FileMode.Create, FileAccess.Write))
{
stream.CopyTo(fileStream);
}
}
19
Source : Source.cs
with MIT License
from ChilliCream
with MIT License
from ChilliCream
public static Source FromStream(Stream stream)
{
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
memoryStream.Position = 0;
var reader = new StreamReader(stream, Encoding.UTF8);
return new Source(reader.ReadToEnd());
}
}
19
Source : CloudMessageSerializer.cs
with Apache License 2.0
from chkr1011
with Apache License 2.0
from chkr1011
public ArraySegment<byte> Compress(ArraySegment<byte> data)
{
// Do not use Brotli compression here because the drawback of the smaller size (in
// comparison with GZIP) is that compression takes up to 44x times of GZIP. The Pi3 will
// require 15 seconds for just 350 KB of data!
// We could also use GZIP but it is just DEFLATE+Checksum. Since TCP is reliable enough with
// its own checksums we can choose DEFLATE.
using (var outputBuffer = new MemoryStream(data.Count))
{
using (var inputBuffer = new MemoryStream(data.Array, data.Offset, data.Count, false))
using (var compressor = new DeflateStream(outputBuffer, CompressionLevel.Fastest, true))
{
inputBuffer.CopyTo(compressor);
}
return new ArraySegment<byte>(outputBuffer.GetBuffer(), 0, (int)outputBuffer.Length);
}
}
19
Source : CloudMessageSerializer.cs
with Apache License 2.0
from chkr1011
with Apache License 2.0
from chkr1011
public ArraySegment<byte> Decompress(ArraySegment<byte> data)
{
using (var outputBuffer = new MemoryStream(data.Count * 2))
{
using (var inputBuffer = new MemoryStream(data.Array, data.Offset, data.Count, false))
using (var decompressor = new DeflateStream(inputBuffer, CompressionMode.Decompress, false))
{
decompressor.CopyTo(outputBuffer);
}
return new ArraySegment<byte>(outputBuffer.GetBuffer(), 0, (int)outputBuffer.Length);
}
}
19
Source : FlvMethod.cs
with GNU General Public License v2.0
from CHKZL
with GNU General Public License v2.0
from CHKZL
public static int 修复flvMetaData(string[] args)
{
CmdModel model = new CmdModel();
CommandLineParser<CmdModel> parser = new CommandLineParser<CmdModel>(model);
parser.CaseSensitive = false;
parser.replacedignmentSyntax = true;
parser.WriteUsageOnError = true;
if (!parser.Parse(args))
return 1;
if (model.FixMetadata && model.RemoveMetadata)
{
Console.WriteLine("fixMeta and noMeta flags conflicts.");
return 1;
}
if (model.FromSeconds.HasValue && model.ToSeconds.HasValue && model.FromSeconds.Value >= model.ToSeconds.Value)
{
Console.WriteLine("Start of output window (from) should be larger than end (to).");
return 1;
}
Console.WriteLine("Input file: {0}", model.InputFile);
Stream inputStream;
if (model.OutputFile == null)
{
Console.WriteLine("Loading whole file to memory.");
inputStream = new MemoryStream();
using (FileStream fs = new FileStream(model.InputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
fs.CopyTo(inputStream);
inputStream.Position = 0;
}
else
inputStream = new FileStream(model.InputFile, FileMode.Open, FileAccess.Read, FileShare.Read);
DateTime fileDate = File.GetLastWriteTime(model.InputFile);
FLVFile file = new FLVFile(inputStream);
file.PrintReport();
//if (model.FromSeconds.HasValue)
// file.CutFromStart(TimeSpan.FromSeconds(model.FromSeconds.Value));
//if (model.ToSeconds.HasValue)
// file.CutToEnd(TimeSpan.FromSeconds(model.ToSeconds.Value));
//if (model.FilterPackets)
// file.FilterPackets();
////if (model.FixTimestamps)
// file.FixTimeStamps();
////if (model.FixMetadata)
// file.FixMetadata();
//if (model.RemoveMetadata)
// file.RemoveMetadata();
file.FilterPackets();
file.FixTimeStamps();
file.FixMetadata();
//if (!(model.FilterPackets || model.FixMetadata || model.FixTimestamps || model.RemoveMetadata || model.FromSeconds.HasValue || model.ToSeconds.HasValue))
//{
// Console.WriteLine("No actions set. Exiting.");
// return 0;
//}
string outputFile = model.OutputFile ?? model.InputFile;
Console.WriteLine("Writing: {0}", outputFile);
file.Write(outputFile);
inputStream.Dispose();
if (model.PreserveDate)
File.SetLastWriteTime(outputFile, fileDate);
return 0;
}
19
Source : NativeHostBase.cs
with MIT License
from chromelyapps
with MIT License
from chromelyapps
protected virtual IntPtr GetIconHandle()
{
var hIcon = IconHandler.LoadIconFromFile(_options.RelativePathToIconFile);
try
{
if (hIcon == null)
{
var replacedembly = replacedembly.GetEntryreplacedembly();
var iconAsResource = replacedembly?.GetManifestResourceNames()
.FirstOrDefault(res => res.EndsWith(_options.RelativePathToIconFile));
if (iconAsResource != null)
{
using (var resStream = replacedembly.GetManifestResourceStream(iconAsResource))
{
using(var fileStream = new FileStream(_options.RelativePathToIconFile, FileMode.Create))
{
resStream?.CopyTo(fileStream);
}
}
}
hIcon = IconHandler.LoadIconFromFile(_options.RelativePathToIconFile);
}
}
catch
{
// ignore
}
return hIcon ?? LoadIconW(IntPtr.Zero, (IntPtr)IDI_APPLICATION);
}
19
Source : DataCore2Util.cs
with GNU General Public License v3.0
from CitizensReactor
with GNU General Public License v3.0
from CitizensReactor
public static byte[] Decompress(byte[] data)
{
byte[] decompressedArray = null;
try
{
using (MemoryStream decompressedStream = new MemoryStream())
{
using (MemoryStream compressStream = new MemoryStream(data))
{
using (DeflateStream deflateStream = new DeflateStream(compressStream, CompressionMode.Decompress))
{
deflateStream.CopyTo(decompressedStream);
}
}
decompressedArray = decompressedStream.ToArray();
}
}
catch (Exception)
{
}
return decompressedArray;
}
19
Source : LocalFilesystemEntry.cs
with GNU General Public License v3.0
from CitizensReactor
with GNU General Public License v3.0
from CitizensReactor
public byte[] GetData()
{
if (IsDirectory)
{
throw new Exception("Can't get data on folders");
}
var filePath = Path.Combine(LocalFilesystem.LocalDirectoryPath, Filepath);
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (MemoryStream ms = new MemoryStream())
{
fs.CopyTo(ms);
var data = ms.ToArray();
return data;
}
}
19
Source : BridgeConfigurationFile.cs
with GNU Affero General Public License v3.0
from clemenskoprolin
with GNU Affero General Public License v3.0
from clemenskoprolin
public static async Task<bool> ReadBridgeConfigurationFile()
{
if (BridgeInformation.demoMode)
return true;
bool completelySuccessful = true; //Is set to false, when when one or all variable cannot be readed.
brigeConfigurationFile = await storageFolder.GetFileAsync(bridgeConfigurationFileName);
byte[] fileInput;
using (Stream stream = await brigeConfigurationFile.OpenStreamForReadAsync())
{
using (MemoryStream memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
fileInput = memoryStream.ToArray();
}
stream.Dispose();
}
try
{
string jsonInput = Cryptographyreplacedistant.DecryptStringAes(fileInput);
JsonObject jsonObject = JsonObject.Parse(jsonInput);
try
{
bridgeConfigurationData.bridgeIPAddress = jsonObject.GetNamedString("bridgeIPAddress");
}
catch
{
bridgeConfigurationData.bridgeIPAddress = "";
completelySuccessful = false;
}
try
{
bridgeConfigurationData.bridgeAppKey = jsonObject.GetNamedString("bridgeAppKey");
}
catch
{
bridgeConfigurationData.bridgeAppKey = "";
completelySuccessful = false;
}
}
catch
{
completelySuccessful = false;
};
return completelySuccessful;
}
19
Source : GZipCompression.cs
with MIT License
from Cloet
with MIT License
from Cloet
public FileInfo Decompress(FileInfo fileToDecompress, FileInfo outputfile)
{
try
{
using (var originalFileStream = fileToDecompress.OpenRead())
{
if ((System.IO.File.GetAttributes(fileToDecompress.FullName) &FileAttributes.Hidden) != FileAttributes.Hidden)
{
if (string.IsNullOrEmpty(outputfile.FullName) || outputfile.Exists)
throw new Exception("File already exists.");
using (var decompressedFileStream = outputfile?.Create())
{
using (var decompressionStream =new System.IO.Compression.GZipStream(originalFileStream, System.IO.Compression.CompressionMode.Decompress))
{
decompressionStream.CopyTo(decompressedFileStream);
}
return outputfile;
}
}
throw new Exception("The file cannot be decompressed.");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
19
Source : DeflateByteCompression.cs
with MIT License
from Cloet
with MIT License
from Cloet
public byte[] DecompressBytes(byte[] data)
{
var input = new MemoryStream(data);
var output = new MemoryStream();
using (var stream = new DeflateStream(input, CompressionMode.Decompress))
{
stream.CopyTo(output);
}
return output.ToArray();
}
19
Source : GZipCompression.cs
with MIT License
from Cloet
with MIT License
from Cloet
public FileInfo Compress(FileInfo fileToCompress, FileInfo outputFile)
{
try
{
if (fileToCompress.Extension == Extension)
throw new ArgumentException(fileToCompress.Name + " is already compressed.");
//var compressedFile = new FileInfo(outputPath + Path.DirectorySeparatorChar + fileToCompress.Name + Extension);
using (var originalFileStream = fileToCompress.OpenRead())
{
if ((System.IO.File.GetAttributes(fileToCompress.FullName) &FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != Extension)
{
using (var compressedFileStream = outputFile.Create())
{
using (var compressionStream = new System.IO.Compression.GZipStream(compressedFileStream, System.IO.Compression.CompressionLevel.Optimal))
{
originalFileStream.CopyTo(compressionStream);
}
}
return outputFile;
}
throw new ArgumentException(fileToCompress.Name + " is not a valid file to compress.");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
19
Source : BinaryDataUtilities.cs
with Apache License 2.0
from cloudevents
with Apache License 2.0
from cloudevents
public static ReadOnlyMemory<byte> ToReadOnlyMemory(Stream stream)
{
Validation.CheckNotNull(stream, nameof(stream));
// TODO: Optimize if it's already a MemoryStream? Will only work in some cases,
// and is most likely to occur in tests, where the efficiency doesn't matter as much.
var memory = new MemoryStream();
stream.CopyTo(memory);
// It's safe to use memory.GetBuffer() and memory.Position here, as this is a stream
// we've created using the parameterless constructor.
var buffer = memory.GetBuffer();
return new ReadOnlyMemory<byte>(buffer, 0, (int)memory.Position);
}
19
Source : WebDownload.cs
with MIT License
from CmlLib
with MIT License
from CmlLib
internal void DownloadFileLimit(string url, string path)
{
string? directoryName = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(directoryName))
Directory.CreateDirectory(directoryName);
var req = WebRequest.CreateHttp(url);
req.Method = "GET";
req.Timeout = 5000;
req.ReadWriteTimeout = 5000;
req.ContinueTimeout = 5000;
var res = req.GetResponse();
using (var httpStream = res.GetResponseStream())
using (var fs = File.OpenWrite(path))
{
httpStream.CopyTo(fs);
}
}
19
Source : AbpStreamExtensions.cs
with GNU Lesser General Public License v3.0
from cnAbp
with GNU Lesser General Public License v3.0
from cnAbp
public static byte[] GetAllBytes(this Stream stream)
{
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
See More Examples