本文整理汇总了C#中System.Byte.Take方法的典型用法代码示例。如果您正苦于以下问题:C# Byte.Take方法的具体用法?C# Byte.Take怎么用?C# Byte.Take使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Byte
的用法示例。
在下文中一共展示了Byte.Take方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetFile
public byte[] GetFile(string serverKey, string hardwareKey, string filePath, string fileType, long chunkOffset, long chuckSize, string version)
{
if (fileType == "layout")
{
var bytes = File.ReadAllBytes(AppPath + filePath);
return bytes;
//var text = File.ReadAllText(AppPath + filePath);
//return text.Select(f => (byte)(f)).ToArray();
//using (var stream = new StreamReader(HttpContext.Current.Server.MapPath("~/Media/" + filePath)))//return actual byte stream
//{
// var allbytes = stream.ReadToEnd().Select(f=> (byte)(f)).ToArray();
// return allbytes;
//}
}
else
{
try
{
using (var stream = new FileStream((System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + ServerPath + filePath), FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite))//return actual byte stream
{
stream.Seek(chunkOffset, SeekOrigin.Begin);
Byte[] documentcontents = new Byte[chuckSize];
int actual = stream.Read(documentcontents, 0, (int)chuckSize);
return documentcontents.Take(actual).ToArray();
}
}
catch (Exception)
{
return new byte[0];
}
}
}
示例2: KeyDer
public static Byte[] KeyDer(Byte[] key)
{
if (key.Length == 16)
return key;
else
return key.Take(16).ToArray();
}
示例3: OnRead
static void OnRead(List<Byte> queue, Byte[] buffer, int count)
{
lock (((ICollection)queue).SyncRoot)
{
queue.AddRange(buffer.Take(count));
}
}
示例4: ReadAll
public static Byte[] ReadAll(this Stream stream, Int32 bufferSize)
{
IEnumerable<Byte> ret = Enumerable.Empty<Byte>();
Byte[] buffer = new Byte[bufferSize];
for (Int32 length; (length = stream.Read(buffer, 0, bufferSize)) != 0; )
{
ret = ret.Concat(buffer.Take(length).ToArray());
if (length < bufferSize)
{
break;
}
}
return ret.ToArray();
}
示例5: FileReceiver
//Метод потока
protected void FileReceiver()
{
//Создаем Listener на порт "по умолчанию"
TcpListener Listen = new TcpListener(6999);
//Начинаем прослушку
Listen.Start();
//и заведем заранее сокет
Socket ReceiveSocket;
while (true)
{
try
{
//Пришло сообщение
ReceiveSocket = Listen.AcceptSocket();
Byte[] Receive = new Byte[256];
//Читать сообщение будем в поток
using (MemoryStream MessageR = new MemoryStream())
{
//Количество считанных байт
Int32 ReceivedBytes;
Int32 Firest256Bytes = 0;
String FilePath = "";
do
{//Собственно читаем
ReceivedBytes = ReceiveSocket.Receive(Receive, Receive.Length, 0);
//Разбираем первые 256 байт
if (Firest256Bytes < 256)
{
Firest256Bytes += ReceivedBytes;
Byte[] ToStr = Receive;
//Учтем, что может возникнуть ситуация, когда они не могу передаться "сразу" все
if (Firest256Bytes > 256)
{
Int32 Start = Firest256Bytes - ReceivedBytes;
Int32 CountToGet = 256 - Start;
Firest256Bytes = 256;
//В случае если было принято >256 байт (двумя сообщениями к примеру)
//Остаток (до 256) записываем в "путь файла"
ToStr = Receive.Take(CountToGet).ToArray();
//А остальную часть - в будующий файл
Receive = Receive.Skip(CountToGet).ToArray();
MessageR.Write(Receive, 0, ReceivedBytes);
}
//Накапливаем имя файла
FilePath += Encoding.Default.GetString(ToStr);
} else
//и записываем в поток
MessageR.Write(Receive, 0, ReceivedBytes);
//Читаем до тех пор, пока в очереди не останется данных
} while (ReceivedBytes == Receive.Length);
//Убираем лишние байты
String resFilePath = FilePath.Substring(0, FilePath.IndexOf('\0'));
using (var File = new FileStream(resFilePath, FileMode.Create))
{//Записываем в файл
File.Write(MessageR.ToArray(), 0, MessageR.ToArray().Length);
}//Уведомим пользователя
ChatBox.BeginInvoke(AcceptDelegate, new object[] { "Received: " + resFilePath, ChatBox });
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
示例6: CheckSig
private Boolean CheckSig(Byte[] sig, PublicKey pubKey, UInt32 txInIndex, Script subScript, Transaction tx)
{
HashType hashType = (HashType)sig.Last();
sig = sig.Take(sig.Length - 1).ToArray();
Transaction txCopy = tx.CopyForSigning(txInIndex, subScript, hashType);
Byte[] txHash = txCopy.ToBytes().Concat(new Byte[] { (Byte)hashType, 0x00, 0x00, 0x00 }).ToArray();
txHash = sha256.ComputeHash(sha256.ComputeHash(txHash));
return pubKey.VerifySignature(txHash, sig);
}
示例7: GetDerivedKeyBytes_PBKDF2_HMACSHA512
/// <summary>
/// Derive Key Bytes using PBKDF2 specification listed in Rfc2898 and HMACSHA512 as the underlying PRF (Psuedo Random Function)
/// </summary>
/// <param name="keyLength">Length in Bytes of Derived Key</param>
/// <returns>Derived Key</returns>
public Byte[] GetDerivedKeyBytes_PBKDF2_HMACSHA512(Int32 keyLength)
{
//no need to throw exception for dkLen too long as per spec because dkLen cannot be larger than Int32.MaxValue so not worth the overhead to check
dkLen = keyLength;
Double l = Math.Ceiling((Double)dkLen / hLen);
Byte[] finalBlock = new Byte[0];
for (Int32 i = 1; i <= l; i++)
{
//Concatenate each block from F into the final block (T_1..T_l)
finalBlock = pMergeByteArrays(finalBlock, F(P, S, c, i));
}
//returning DK note r not used as dkLen bytes of the final concatenated block returned rather than <0...r-1> substring of final intermediate block + prior blocks as per spec
return finalBlock.Take(dkLen).ToArray();
}
示例8: FileReceiver
//Метод потока
protected void FileReceiver()
{
//Создаем Listener на порт "по умолчанию"
TcpListener Listen = new TcpListener(Int32.Parse(PORT.Text));
//и заведем заранее сокет
Socket ReceiveSocket;
try
{
//Начинаем прослушку
Listen.Start();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
while (true)
{
try
{
//Пришло сообщение
ReceiveSocket = Listen.AcceptSocket();
Byte[] Receive = new Byte[QuantityByteInStep];
//Читать сообщение будем в поток
using (MemoryStream MessageR = new MemoryStream())
{
//Количество считанных байт
Int32 ReceivedBytes;
Int32 FirestQuantityByteInStepBytes = 0;
String FilePath = "";
//Если true, то первые QuantityByteInStep прочитаны
bool firstBytes = false;
string resFilePath = "";
string resFileSize = "";
do
{//Собственно читаем
ReceivedBytes = ReceiveSocket.Receive(Receive, Receive.Length, 0);
//Разбираем первые QuantityByteInStep байт
if (FirestQuantityByteInStepBytes < QuantityByteInStep)
{
FirestQuantityByteInStepBytes += ReceivedBytes;
Byte[] ToStr = Receive;
//Учтем, что может возникнуть ситуация, когда они не могу передаться "сразу" все
if (FirestQuantityByteInStepBytes > QuantityByteInStep)
{
Int32 Start = FirestQuantityByteInStepBytes - ReceivedBytes;
Int32 CountToGet = QuantityByteInStep - Start;
FirestQuantityByteInStepBytes = QuantityByteInStep;
//В случае если было принято >QuantityByteInStep байт (двумя сообщениями к примеру)
//Остаток (до QuantityByteInStep) записываем в "путь файла"
ToStr = Receive.Take(CountToGet).ToArray();
//А остальную часть - в будующий файл
Receive = Receive.Skip(CountToGet).ToArray();
MessageR.Write(Receive, 0, ReceivedBytes);
firstBytes = true;
}
//Накапливаем имя файла
FilePath += Encoding.Default.GetString(ToStr);
}
else
{
if (firstBytes || FirestQuantityByteInStepBytes == QuantityByteInStep)
{
//Уже можем прочитать имя и разме рфайла
//Убираем лишние байты
String resFilePathAndFileSize = FilePath.Substring(0, FilePath.IndexOf('\0'));
char[] separators = { '^' };
string[] words = resFilePathAndFileSize.Split(separators);
resFilePath = words[0];
resFileSize = words[1];
firstBytes = false;
FirestQuantityByteInStepBytes = QuantityByteInStep + 1;
ChatBox.BeginInvoke(AcceptDelegate, new object[] { "Началось принятие файла. " + resFilePath, ChatBox });
}
//и записываем в поток
MessageR.Write(Receive, 0, ReceivedBytes);
}
//Читаем до тех пор, пока в очереди не останется данных
} while (ReceivedBytes > 0);
string tempFilePath;
if (filePath != "")
{
tempFilePath = filePath + "//" + resFilePath;
}
else
{
tempFilePath = resFilePath;
}
using (var File = new FileStream(tempFilePath, FileMode.Create))
{
//Записываем в файл
File.Write(MessageR.ToArray(), 0, MessageR.ToArray().Length);
//.........这里部分代码省略.........
示例9: FromBufferBytes
/// <summary>
/// Восстанавливает CAN-сообщение из буфера АППИ
/// </summary>
/// <param name="Buff">10 байт буфера</param>
public static CanFrame FromBufferBytes(Byte[] Buff)
{
int id = (int)BitConverter.ToUInt16(Buff.Take(2).Reverse().ToArray(), 0) >> 4;
int len = Buff[1] & 0x0f;
if (len > 8) throw new AppiBufferDecodeException("Расшифрована неправильная длина CAN-сообщения ({0} байт)", len);
return CanFrame.NewWithId(id, Buff, 2, len);
}
示例10: CreateTextBlock
internal byte[] CreateTextBlock( int Size )
{
UInt32 TextLocationRelative = Header.TextLocation - Header.TextOffsetsLocation;
Byte[] bytes = new Byte[Size];
TextEntries.Sort();
UInt16 CurrentTextOffset = 0;
foreach ( LuxPainEvtText t in TextEntries ) {
byte[] CurrentTextOffsetBytes = BitConverter.GetBytes( (UInt16)( CurrentTextOffset ) );
CurrentTextOffsetBytes.CopyTo( bytes, t.OffsetLocation - Header.TextOffsetsLocation );
byte[] text = LuxPainUtil.BackConvertLuxPainText( t.Text );
text.CopyTo( bytes, TextLocationRelative );
TextLocationRelative += (uint)text.Length;
CurrentTextOffset += (ushort)( text.Length / 2 );
}
return bytes.Take( (int)TextLocationRelative ).ToArray();
}
示例11: Decode
public unsafe String Decode(Byte* start, Byte* end)
{
var current = start;
var buffer = new Byte[end - current];
Int32 index = 0;
Byte* rfc2047Start = null;
Byte* rfc2047Current = null;
Rfc2047ParsingState state = Rfc2047ParsingState.NotPasing;
Encoding charset = null;
Rfc2047Encoding? encoding = null;
Int32 whiteSpaceCount = 0;
StringBuilder sb = new StringBuilder(buffer.Length);
while (current < end)
{
switch (state)
{
case Rfc2047ParsingState.NotPasing:
#region
if (*current == '=')
{
state = Rfc2047ParsingState.Start;
rfc2047Start = current;
}
break;
#endregion
case Rfc2047ParsingState.Start:
#region
if (*current == '?')
{
state = Rfc2047ParsingState.Charset;
rfc2047Current = current + 1;
}
else
{
state = Rfc2047ParsingState.NotPasing;
}
break;
#endregion
case Rfc2047ParsingState.Charset:
#region
if (*current == '?')
{
var bb = CreateNewBytes(new IntPtr(rfc2047Current), current - rfc2047Current);
charset = EncodingDictionary.Current.GetEncoding(this.Encoding.GetString(bb));
if (charset == null)
{
state = Rfc2047ParsingState.NotPasing;
rfc2047Current = null;
}
else
{
state = Rfc2047ParsingState.BorQ;
rfc2047Current = current + 1;
}
}
break;
#endregion
case Rfc2047ParsingState.BorQ:
#region
if (*current == '?')
{
var bb = CreateNewBytes(new IntPtr(rfc2047Current), current - rfc2047Current);
var BorQ = this.Encoding.GetString(bb).ToUpper();
if (BorQ == "B" || BorQ == "Q")
{
switch (BorQ)
{
case "B": encoding = Rfc2047Encoding.Base64; break;
case "Q": encoding = Rfc2047Encoding.QuotedPrintable; break;
default: throw new InvalidOperationException();
}
state = Rfc2047ParsingState.Value;
rfc2047Current = current + 1;
}
else
{
state = Rfc2047ParsingState.NotPasing;
rfc2047Current = null;
}
}
break;
#endregion
case Rfc2047ParsingState.Value:
#region
if (*current == '?')
{
state = Rfc2047ParsingState.ValueEnd;
}
break;
#endregion
case Rfc2047ParsingState.ValueEnd:
#region
if (*current == '=')
{
sb.Append(this.Encoding.GetString(buffer.Take(index).ToArray()));
index = 0;
var bb = CreateNewBytes(new IntPtr(rfc2047Current), current - rfc2047Current - 1);
switch (encoding)
//.........这里部分代码省略.........
示例12: AreEqual
private Boolean AreEqual(Stream stream1, Stream stream2)
{
stream1.Position = stream2.Position = 0;
var buffer1 = new Byte[8192];
var buffer2 = new Byte[8192];
for (; ; )
{
var read1 = stream1.Read(buffer1, 0, buffer1.Length);
var read2 = stream2.Read(buffer2, 0, buffer2.Length);
if (read1 != read2)
return false;
if (read1 == 0)
break;
if (!Enumerable.SequenceEqual(buffer1.Take(read1), buffer2.Take(read2)))
return false;
}
return true;
}
示例13: GetMessage
public int GetMessage(byte[] prvkey, byte[] pubkey, Action<Message>store)
{
int count = 0;
sw.WriteByte((byte)ClientServerCmd.GetMessage);
SendPublicKey(pubkey);
RSAParameters rsap;
Shared.LoadKey2(Shared.prvToPem(prvkey), null, out rsap);
Shared.AnswerRemotePubkeyTest(sr, sw, rsap);
while (true)
{
var resp = sr.ReadByte();
if (resp == (byte)ClientServerCmd.NoMessage)
return count;
else if (resp != (byte)ClientServerCmd.HasMessage)
throw new Exception();
var len = sr.ReadShort();
if (len > 1024)
throw new Exception();
var buf = new Byte[len];
//sr.Read(buf, 0, 8);
//var ts = BitConverter.ToInt64(buf, 0);
//DateTime.FromFileTimeUtc(ts);
if (sr.Read(buf, 0, len) != len)
throw new Exception();
byte[] aeskey,aesIV,aesbuf;
using (var rsa = new RSACryptoServiceProvider())
{
rsa.ImportParameters(rsap);
var rsalen = 128;
var rsabuf = buf.Take(rsalen).ToArray();
aesbuf = buf.Skip(rsalen).ToArray();
var aes_keyivdata = rsa.Decrypt(rsabuf, false);
aeskey = aes_keyivdata.Take(32).ToArray();
aesIV = aes_keyivdata.Skip(32).Take(16).ToArray();
}
var msg=DecodeMessage(aesbuf,aeskey, aesIV, rsap, pubkey);
store(msg);
count++;
sw.WriteByte((Byte)ClientServerCmd.Success);
}
}
示例14: ImageLoad
MatrixValue ImageLoad(String filename, out Boolean error, Double coarsening = Double.NaN)
{
error = false;
var imageType = String.Empty;
using (var fs = File.Open(filename, FileMode.Open))
{
var file_bytes = new Byte[fs.Length];
fs.Read(file_bytes, 0, 8);
var png_magic_number = new Byte[] { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };
if (!file_bytes.Take(8).Select((b, i) => b == png_magic_number[i]).Contains(false))
imageType = "png";
var tiff_magic_number_0 = new Byte[] { 0x49, 0x49, 0x2a, 0x00 };
if (!file_bytes.Take(4).Select((b, i) => b == tiff_magic_number_0[i]).Contains(false))
imageType = "tiff";
var tiff_magic_number_1 = new Byte[] { 0x4d, 0x4d, 0x2a, 0x00 };
if (!file_bytes.Take(4).Select((b, i) => b == tiff_magic_number_1[i]).Contains(false))
imageType = "tiff";
var bmp_magic_number = new Byte[] { 0x42, 0x4D };
if (!file_bytes.Take(2).Select((b, i) => b == bmp_magic_number[i]).Contains(false))
imageType = "bmp";
var gif_magic_number_0 = new Byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 };
if (!file_bytes.Take(6).Select((b, i) => b == gif_magic_number_0[i]).Contains(false))
imageType = "gif";
var gif_magic_number_1 = new Byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 };
if (!file_bytes.Take(6).Select((b, i) => b == gif_magic_number_1[i]).Contains(false))
imageType = "gif";
var jpg_magic_number = new Byte[] { 0xff, 0xd8 };
if (!file_bytes.Take(2).Select((b, i) => b == jpg_magic_number[i]).Contains(false))
imageType = "jpg";
}
if (imageType == String.Empty)
{
error = true;
return new MatrixValue();
}
using (var bmp = new Bitmap(filename))
{
var result = default(MatrixValue);
if (bmp == null)
{
error = true;
result = new MatrixValue();
}
else
{
var height = bmp.Height;
var width = bmp.Width;
var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
var bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
var ptr = bmpData.Scan0;
var bytes = Math.Abs(bmpData.Stride) * bmp.Height;
var rgbValues = new Byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
bmp.UnlockBits(bmpData);
var bytesPerPixel = 0;
if (bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Canonical ||
bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb ||
bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppPArgb ||
bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppRgb)
{
bytesPerPixel = 4;
}
else if (bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb)
{
bytesPerPixel = 3;
}
else
{
throw new YAMPPixelFormatNotSupportedException(filename);
}
if (Double.IsNaN(coarsening))
{
const Double maxPixelPerDirection = 100.0;
if (width > maxPixelPerDirection || height > maxPixelPerDirection)
{
coarsening = Math.Max(width / maxPixelPerDirection, height / maxPixelPerDirection);
}
else
//.........这里部分代码省略.........