本文整理汇总了C#中Stream.Read方法的典型用法代码示例。如果您正苦于以下问题:C# Stream.Read方法的具体用法?C# Stream.Read怎么用?C# Stream.Read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Stream
的用法示例。
在下文中一共展示了Stream.Read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ReadMetaData
public ImageMetaData ReadMetaData(Stream stream)
{
var header = new byte[0x20];
if (0x20 != stream.Read(header, 0, 0x20))
return null;
if (!Binary.AsciiEqual(header, 0, "xtx\0"))
{
var header_size = LittleEndian.ToUInt32(header, 0);
if (header_size >= 0x1000) // XXX use some arbitrary "large" value to avoid call to Stream.Length
return null;
stream.Position = header_size;
if (0x20 != stream.Read(header, 0, 0x20))
return null;
if (!Binary.AsciiEqual(header, 0, "xtx\0"))
return null;
}
if (header[4] > 2)
return null;
int aligned_width = BigEndian.ToInt32(header, 8);
int aligned_height = BigEndian.ToInt32(header, 0xC);
if (aligned_width <= 0 || aligned_height <= 0)
return null;
return new XtxMetaData
{
Width = BigEndian.ToUInt32(header, 0x10),
Height = BigEndian.ToUInt32(header, 0x14),
OffsetX = BigEndian.ToInt32(header, 0x18),
OffsetY = BigEndian.ToInt32(header, 0x1C),
BPP = 32,
Format = header[4],
AlignedWidth = aligned_width,
AlignedHeight = aligned_height,
DataOffset = (uint)stream.Position,
};
}
示例2: CheckKeyForMessage
public static long CheckKeyForMessage(Stream keyStream, long messageLength)
{
long messageLengthBits = messageLength * 8;
long countRequiredSamples = 0;
if (messageLengthBits > keyStream.Length)
{
long keyLength = keyStream.Length;
byte[] keyBytes = new byte[keyLength];
keyStream.Read(keyBytes, 0, keyBytes.Length);
countRequiredSamples = SumKeyArray(keyBytes);
double countKeyCopies = messageLengthBits / keyLength;
countRequiredSamples = (long)(countRequiredSamples * countKeyCopies);
}
else
{
byte[] keyBytes = new byte[messageLengthBits];
keyStream.Read(keyBytes, 0, keyBytes.Length);
countRequiredSamples = SumKeyArray(keyBytes);
}
keyStream.Seek(0, SeekOrigin.Begin);
return countRequiredSamples;
}
示例3: ModsDemuxer
public ModsDemuxer(Stream Stream)
{
this.Stream = Stream;
Header = new ModsHeader(Stream);
if (Header.AudioOffset != 0)
{
AudioCodebooks = new byte[Header.NbChannel][];
Stream.Position = Header.AudioOffset;
for (int i = 0; i < Header.NbChannel; i++)
{
AudioCodebooks[i] = new byte[0xC34];
Stream.Read(AudioCodebooks[i], 0, 0xC34);
}
}
KeyFrames = new KeyFrameInfo[Header.KeyframeCount];
Stream.Position = Header.KeyframeIndexOffset;
byte[] tmp = new byte[8];
for (int i = 0; i < Header.KeyframeCount; i++)
{
KeyFrames[i] = new KeyFrameInfo();
Stream.Read(tmp, 0, 8);
KeyFrames[i].FrameNumber = IOUtil.ReadU32LE(tmp, 0);
KeyFrames[i].DataOffset = IOUtil.ReadU32LE(tmp, 4);
}
JumpToKeyFrame(0);
}
示例4: Copy
public static int Copy(Stream source, Stream destination, byte[] buffer, int? mask, int count)
{
int totalRead = 0, read;
if(mask == null)
{
while (count > 0 && (read = source.Read(buffer, 0, Math.Min(count, buffer.Length))) > 0)
{
destination.Write(buffer, 0, read);
totalRead += read;
count -= read;
}
} else
{
int effectiveLength = (buffer.Length/8)*8; // need nice sized! e.g. 100-byte array, can only use 96 bytes
if(effectiveLength == 0) throw new ArgumentException("buffer is too small to be useful", "buffer");
// we read it big-endian, so we need to *write* it big-endian, and then we'll use unsafe code to read the value,
// so that the endian-ness we use is CPU-endian, and so it matches whatever we do below
int maskValue = mask.Value;
buffer[0] = buffer[4] = (byte) (maskValue >> 24);
buffer[1] = buffer[5] = (byte) (maskValue >> 16);
buffer[2] = buffer[6] = (byte) (maskValue >> 8);
buffer[3] = buffer[7] = (byte) maskValue;
unsafe
{
fixed (byte* bufferPtr = buffer) // treat the byte-array as a pile-of-ulongs
{
var longPtr = (ulong*)bufferPtr;
ulong xorMask = *longPtr;
int bytesThisIteration;
do
{
// now, need to fill buffer as much as possible each time, as we want to work in exact
// units of 8 bytes; we don't need to worry about applying the mask to any garbage at the
// end of the buffer, as we simply won't copy that out
int offset = 0, available = effectiveLength;
while (available > 0 && (read = source.Read(buffer, offset, Math.Min(count, available))) > 0)
{
available -= read;
totalRead += read;
count -= read;
offset += read;
}
bytesThisIteration = effectiveLength - available;
int chunks = bytesThisIteration/8;
if ((available%8) != 0) chunks++;
// apply xor 8-bytes at a time, coz we haz 64-bit CPU, baby!
for (int i = 0; i < chunks; i++)
longPtr[i] ^= xorMask;
destination.Write(buffer, 0, bytesThisIteration);
} while (bytesThisIteration != 0);
}
}
}
if(count != 0) throw new EndOfStreamException();
return totalRead;
}
示例5: CreateV1Frames
private void CreateV1Frames(Stream stream)
{
// ID1 header am ende ...
stream.Seek(-125, SeekOrigin.End);
// 30 zeichen title => TIT2
// 30 zeichen artist => TCOM
// 30 zeichen album => TALB
// 4 zeichen jahr => TYER
// 30 zeichen commentar - kann auch den track enthalten (TRCK) - der letzte byte
// 1 byte Genre
// == 125
foreach (var item in new[] { "TIT2", "TCOM", "TALB" })
{
AddFrame(item, ByteHelper.BytesToString(stream.Read(30)));
}
AddFrame("TYER", ByteHelper.BytesToString(stream.Read(4)));
// comment - egal
stream.Seek(28, SeekOrigin.Current);
var track = stream.Read(2);
if (track[0] == 0 && track[1] != 0)
{
// dann ist track[1] eine zahl;
if (track[1] < 48)
{
AddFrame("TRCK",((int)track[1]).ToString());
}
}
}
示例6: Upload
public void Upload(TransferInfo transferInfo, Stream data)
{
// Compute how much will be left over for the last chunk
long dataLength = data.Length;
long chunkSize = SendChunkSize == 0 ? 256000 : SendChunkSize;
long remainder = dataLength % chunkSize;
long chunkCount = dataLength / chunkSize;
// Handle the case of small files
if (chunkSize >= dataLength)
{
chunkSize = dataLength;
remainder = 0;
chunkCount = 1;
}
string sessionId = m_Proxy.BeginUploadSession(transferInfo);
for (long index = 0; index < chunkCount; index++)
{
byte[] chunk = new byte[chunkSize];
data.Read(chunk, (int)(index * chunkSize), (int)chunkSize);
m_Proxy.UploadChunk(sessionId, chunk);
}
if (remainder > 0)
{
byte[] chunk = new byte[remainder];
data.Read(chunk, (int)(chunkCount * chunkSize), (int)remainder);
m_Proxy.UploadChunk(sessionId, chunk);
}
m_Proxy.CompleteUpload(sessionId);
}
示例7: UploadFile
public string UploadFile(string fileName, Stream content)
{
// 我们不知道HTTP请求流的长度,所以我们必须使用以下代码读出流的长度:
int bufferSize = 4096;
int bytesRead = 1;
int totalBytesRead = 0;
try
{
using (FileStream fileStream = File.Create(fileName))
{
byte[] buffer = new byte[bufferSize];
bytesRead = content.Read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
fileStream.Write(buffer, 0, bytesRead);
bytesRead = content.Read(buffer, 0, bufferSize);
totalBytesRead += bytesRead;
}
}
// 按照REST服务的最近实践,当资源被创建时,返回一个201 Created状态代码代理默认的200.
// 这意味着Silverlight客户端必须使用HTTP栈,替代默认的浏览器HTTP栈使用服务来工作.
return WriteResponse(HttpStatusCode.Created, "Created.");
}
catch (Exception ex)
{
return WriteResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
示例8: GetCrc32AndCopy
/// <summary>
/// Returns the CRC32 for the specified stream, and writes the input into the output stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <param name="output">The stream into which to deflate the input</param>
/// <returns>the CRC32 calculation</returns>
public UInt32 GetCrc32AndCopy(Stream input, Stream output)
{
unchecked
{
UInt32 crc32Result;
crc32Result = 0xFFFFFFFF;
byte[] buffer = new byte[BufferSize];
int readSize = BufferSize;
m_TotalBytesRead = 0;
int count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
m_TotalBytesRead += count;
while (count > 0)
{
for (int i = 0; i < count; i++)
{
crc32Result = ((crc32Result) >> 8) ^ m_crc32Table[(buffer[i]) ^ ((crc32Result) & 0x000000FF)];
}
count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
m_TotalBytesRead += count;
}
return ~crc32Result;
}
}
示例9: Decode
// Source: http://blogs.msdn.com/b/feroze_daud/archive/2004/03/30/104440.aspx
public static String Decode(WebResponse response, Stream stream)
{
String charset = null;
String contentType = response.Headers["content-type"];
if(contentType != null)
{
int index = contentType.IndexOf("charset=");
if(index != -1)
{
charset = contentType.Substring(index + 8);
}
}
MemoryStream data = new MemoryStream();
byte[] buffer = new byte[1024];
int read = stream.Read(buffer, 0, buffer.Length);
while(read > 0)
{
data.Write(buffer, 0, read);
read = stream.Read(buffer, 0, buffer.Length);
}
stream.Close();
Encoding encoding = Encoding.UTF8;
try
{
if(charset != null)
encoding = Encoding.GetEncoding(charset);
}
catch { }
data.Seek(0, SeekOrigin.Begin);
StreamReader streamReader = new StreamReader(data, encoding);
return streamReader.ReadToEnd();
}
示例10: Get
public static FileSystemRecord Get(Stream volume, byte[] buffer1, byte[] buffer2, int sector)
{
DirectoryRecord directory;
FileRecord file;
long pos = (long)sector * 512L;
volume.Position = pos;
volume.Read(buffer1, 0, 512);
if (BitConverter.ToUInt32(buffer1, 4) != 1179208773)
{
directory = new DirectoryRecord();
directory.Name = sector.ToString();
Console.WriteLine("Not a FILE record, " + sector + "!");
return directory;
}
pos = (long)BitConverter.ToInt32(buffer1, 8) * 512L;
volume.Position = pos;
volume.Read(buffer2, 0, 512);
switch (BitConverter.ToUInt32(buffer2, 4))
{
case 1179208773: // child is a FILE, it's a dir!
directory = new DirectoryRecord();
FillFileSystemRecord(volume, buffer1, directory);
int next = directory.Child;
while (next != 0)
{
directory.Children.Add(next);
volume.Position = (long)next * 512L;
volume.Read(buffer1, 0, 512);
next = BitConverter.ToInt32(buffer1, 60);
}
return directory;
case 1414677829: // child is a TREE, it's a dir again!
directory = new DirectoryRecord();
FillFileSystemRecord(volume, buffer1, directory);
FillTree(volume, buffer2, directory.Child, sector, directory.Children);
return directory;
case 1095520067: // child is an ALOC, it's a file!
file = new FileRecord();
FillFileSystemRecord(volume, buffer1, file);
file.Allocation = ByteKiller(buffer2, 8, 496);
file.AllocationStart = file.Child + file.Allocation[1];
file.Allocation[1] = 0;
file.UnusedBytes = BitConverter.ToInt32(buffer2, 504);
file.SectorCount = BitConverter.ToInt32(buffer2, 508);
if (file.SectorCount * 512 - file.UnusedBytes != file.Size) Console.WriteLine("File " + sector + " isn't correct size!");
return file;
default: // usually empty file
file = new FileRecord();
FillFileSystemRecord(volume, buffer1, file);
file.Allocation = new int[0];
file.AllocationStart = 0;
file.UnusedBytes = 0;
file.SectorCount = 0;
if (file.Child != 0) Console.WriteLine("Uh, I dunno what's the problem, " + sector + ".");
return file;
}
}
示例11: DecryptStream
/// <summary>
/// Производит дешифрование потока.
/// </summary>
/// <param name="inputStream">Поток, который будет дешифрован.</param>
/// <param name="outputStream">Поток, в который будет записан результат дешифрования.</param>
/// <param name="Key">Ключ для дешифрования.</param>
public void DecryptStream(Stream inputStream, Stream outputStream, byte[] Key)
{
ThrowIfDisposed();
if (inputStream == null || outputStream == null || Key == null)
throw new ArgumentNullException("One of the arguments (or all) equals null");
int maxBufferSizeValue = bufferCoefficient * ConstBufferCoefficient;
byte[] originFileLengthArray = new byte[sizeof(long)];
byte[] iv = new byte[cryptAlgorithm.BlockSize / 8];
inputStream.Read(originFileLengthArray, 0, sizeof(long));
inputStream.Read(iv, 0, cryptAlgorithm.BlockSize / 8);
long deltaLength = inputStream.Length - HeadSize - cryptAlgorithm.BlockSize / 8 - BitConverter.ToInt64(originFileLengthArray, 0);
using (var transform = cryptAlgorithm.CreateDecryptor(Key, iv))
{
using (var csEncrypt = new CryptoStream(inputStream, transform, CryptoStreamMode.Read))
{
var dataBuffer = new byte[maxBufferSizeValue];
while (inputStream.Position < inputStream.Length)
{
int dataSize = (inputStream.Length - inputStream.Position > maxBufferSizeValue) ? maxBufferSizeValue : (int)(inputStream.Length - inputStream.Position - deltaLength);
csEncrypt.Read(dataBuffer, 0, dataSize);
outputStream.Write(dataBuffer, 0, dataSize);
}
}
}
}
示例12: while
Stream lStream = fStorage.GetFile(SecureFileName, 0);
try
{
byte[] lBuffer = new byte[BUFFER_SIZE];
int lBytesRead = lStream.Read(lBuffer, 0, BUFFER_SIZE);
while (lBytesRead > 0)
{
aToStream.Write(lBuffer,0,lBytesRead);
lBytesRead = lStream.Read(lBuffer, 0, BUFFER_SIZE);
}
}
finally
{
lStream.Close();
}
//return new FileStream(SecureFileName,FileMode.Open, FileAccess.Read, FileShare.Read);
}
const int BUFFER_SIZE = 64*1024;
public override void CreateFile(Stream aStream)
{
if (File.Exists(SecureFileName))
throw new Exception("Error adding file to secure storage: file already exist.");
//Stream lStream = new FileStream(SecureFileName,FileMode.CreateNew, FileAccess.Write, FileShare.None);
Stream lStream = fStorage.CreateFile(SecureFileName);
try
{
示例13: Read
public Texture2D Read(Stream inputStream, GraphicsDevice graphicsDevice)
{
if (IsPngImage(inputStream) == false)
{
throw new Exception("File does not have PNG signature.");
}
inputStream.Position = 8;
while (inputStream.Position != inputStream.Length)
{
byte[] chunkDataLengthBytes = new byte[4];
inputStream.Read(chunkDataLengthBytes, 0, 4);
uint chunkDataLength = chunkDataLengthBytes.ToUInt();
inputStream.Position -= 4;
byte[] chunkBytes = new byte[12 + chunkDataLength];
inputStream.Read(chunkBytes, 0, (int)(12 + chunkDataLength));
ProcessChunk(chunkBytes);
}
UnpackDataChunks();
texture = new Texture2D(graphicsDevice, width, height, false, SurfaceFormat.Color);
texture.SetData<Color>(data);
return texture;
}
示例14: FrameScanner
public FrameScanner(Stream input)
{
input.Seek(0, SeekOrigin.Begin);
byte[] frameheadbuffer = new byte[byte.MaxValue + 4];
byte[] buffer = new byte[6];
input.Read(buffer, 0, 6);
headerOkay = Encoding.ASCII.GetString(buffer, 0, 4) == "MMDb";
if (!headerOkay)
return;
version = new Version(buffer[4], buffer[5]);
if (version == FileVersions.First)
{
input.Read(buffer, 0, 4);
id = BitConverter.ToInt32(buffer, 0);
while (input.Position < input.Length)
{
byte b = (byte)input.ReadByte();
input.Read(frameheadbuffer, 0, 4 + b);
FrameIdentifier identifier = new FrameIdentifier(frameheadbuffer, 0, b);
int length = BitConverter.ToInt32(frameheadbuffer, b);
int position = (int)input.Position;
Frame frame = new Frame(position, length, 5 + b);
frames.Add(identifier, frame);
input.Seek(length, SeekOrigin.Current);
}
}
else
{
headerOkay = false;
return;
}
}
示例15: TryRead
public static bool TryRead(Stream stream, out LengthedPrefixedString s)
{
s = null;
if (!MatchHeader(stream))
return false;
var lengthBytes = new byte[4];
if (stream.Read(lengthBytes, 0, 4) < 4)
return false;
int length = BitConverter.ToInt32(lengthBytes, 0);
var stringBytes = new byte[length];
if (stream.Read(stringBytes, 0, length) < length)
return false;
try
{
string data = Encoding.UTF8.GetString(stringBytes);
s = new LengthedPrefixedString(data);
}
catch
{
return false;
}
if (!HasTerminator(stream))
return false;
return true;
}