本文整理汇总了C#中System.IO.MemoryStream.Seek方法的典型用法代码示例。如果您正苦于以下问题:C# MemoryStream.Seek方法的具体用法?C# MemoryStream.Seek怎么用?C# MemoryStream.Seek使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.MemoryStream
的用法示例。
在下文中一共展示了MemoryStream.Seek方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: it_should_serialize_and_deserialize_the_Person_object
public void it_should_serialize_and_deserialize_the_Person_object()
{
var ser = new XmlSerializer(typeof(Person));
var stream = new MemoryStream();
var dataManager = new DataRepositoryDummy();
var people = dataManager.GetPeopleWithPets();
var person = people.First(x => x.Name.ToLower() == "jpol");
// person.Nickname = "octopus";
ser.Serialize(stream, person);
var xml = UTF8Encoding.UTF8.GetString(stream.ToArray());
xml.Should().NotBeBlank();
Console.WriteLine(xml);
stream.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(stream);
var xmlRead = reader.ReadToEnd();
xml.Should().Be(xmlRead);
stream.Seek(0, SeekOrigin.Begin);
var deserializedPerson = ser.Deserialize(new StreamReader(stream)) as Person;
deserializedPerson.Should().NotBeNull();
deserializedPerson.Name.Should().Be(person.Name);
}
示例2: CopyTo1
public unsafe void CopyTo1()
{
const int bufferSize = 10;
byte* buffer = (byte*)Marshal.AllocHGlobal(bufferSize);
try
{
var s = new MemoryStream(new byte[] { 0, 1, 2, 3, 4 });
InvalidateMemory(buffer, bufferSize);
s.Seek(0, SeekOrigin.Begin);
s.CopyTo(buffer, 3);
Assert.Equal(new byte[] { 0, 1, 2 }, ReadBuffer(buffer, bufferSize));
InvalidateMemory(buffer, bufferSize);
s.Seek(0, SeekOrigin.Begin);
s.CopyTo(buffer, 0);
Assert.Equal(new byte[0], ReadBuffer(buffer, bufferSize));
InvalidateMemory(buffer, bufferSize);
s.Seek(0, SeekOrigin.Begin);
s.CopyTo(buffer, 5);
Assert.Equal(new byte[] { 0, 1, 2, 3, 4 }, ReadBuffer(buffer, bufferSize));
Assert.Throws<IOException>(() => s.CopyTo(buffer, 6));
}
finally
{
Marshal.FreeHGlobal((IntPtr)buffer);
}
}
示例3: AddFile
public void AddFile(DeduplicatorState state, FileInfo sourceFile, string destinationPath)
{
if (state.DestinationToFileHash.ContainsKey(destinationPath))
{
// File has already been added.
return;
}
// Read the source file.
var memory = new MemoryStream();
using (var stream = new BufferedStream(new FileStream(sourceFile.FullName, FileMode.Open, FileAccess.Read, FileShare.None), 1200000))
{
stream.CopyTo(memory);
}
// Hash the memory stream.
var sha1 = new SHA1Managed();
memory.Seek(0, SeekOrigin.Begin);
var hashBytes = sha1.ComputeHash(memory);
var hashString = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
memory.Seek(0, SeekOrigin.Begin);
// Add to the file hash -> source map if not already present.
if (!state.FileHashToSource.ContainsKey(hashString))
{
state.FileHashToSource.Add(hashString, memory);
}
else
{
memory.Dispose();
}
state.DestinationToFileHash.Add(destinationPath, hashString);
}
示例4: UploadFile
/// <summary>
/// Upload a file to the blobs storage and create a record in the files table
/// </summary>
/// <param name="fileToLoad"></param>
/// <returns>The token to be used to access the file later on</returns>
public UploadFileTokenMessage UploadFile(UploadFileContentMessage fileToLoad)
{
// generate random 6 digits password
string password = GeneratePassword();
// remove bad characters from sender name
string safeSenderName = GetSafeSenderName(fileToLoad.SenderName);
using (MemoryStream memoryStream = new MemoryStream())
{
Utils.CopyStream(fileToLoad.FileByteStream, memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
// make sure stream is a valid deck
if (!IsLegalDeckFile(memoryStream))
{
return new UploadFileTokenMessage() { Password = string.Empty };
}
memoryStream.Seek(0, SeekOrigin.Begin);
// save stream as blob
var blobUri = CreateBlob(memoryStream, password + safeSenderName);
var files_ds = new FilesDataSource();
var token = files_ds.AddFile(password + safeSenderName, ContainerName, blobUri);
}
return new UploadFileTokenMessage() { Password = password };
}
示例5: getName
/// <summary>
/// Gets the name of the first model on a CGFX file.
/// Returns null if the file doesn't contain any model.
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string getName(MemoryStream data)
{
BinaryReader input = new BinaryReader(data);
cgfxHeader header = new cgfxHeader();
header.magic = IOUtils.readString(input, 0, 4);
header.endian = input.ReadUInt16();
header.length = input.ReadUInt16();
header.revision = input.ReadUInt32();
header.fileLength = input.ReadUInt32();
header.entries = input.ReadUInt32();
data.Seek(header.length + 8, SeekOrigin.Begin);
List<dictEntry> models = getDictionary(input);
if (models.Count > 0)
{
data.Seek(models[0].dataOffset + 0xc, SeekOrigin.Begin);
string name = IOUtils.readString(input, getRelativeOffset(input));
data.Close();
return name;
}
else
{
data.Close();
return null;
}
}
示例6: DownloadBlob
private static string DownloadBlob(CloudBlockBlob blob)
{
using (var stream = new MemoryStream())
{
StreamReader reader;
try
{
blob.DownloadToStream(stream, options: new BlobRequestOptions()
{
RetryPolicy = new LinearRetry(TimeSpan.FromSeconds(5), 3)
});
}
catch (StorageException se)
{
return "";
}
try
{
stream.Seek(0, 0);
reader = new StreamReader(new GZipStream(stream, CompressionMode.Decompress));
return reader.ReadToEnd();
}
catch
{
stream.Seek(0, 0);
reader = new StreamReader(stream);
return reader.ReadToEnd();
}
}
}
示例7: AddReviewJSON
public string AddReviewJSON(Stream indata, string pid, string key)
{
//Read in the data as it streams in
MemoryStream ms = new MemoryStream();
int pos = 1;
while (pos != -1)
{
pos = indata.ReadByte();
if (pos > -1)
ms.WriteByte((byte)pos);
}
//We now have compleated the streamin in operation
//Read the stream as a string
ms.Seek(0, SeekOrigin.Begin);
byte[] data = new byte[ms.Length];
ms.Read(data, 0, (int)ms.Length);
ms.Seek(0, SeekOrigin.Begin);
string s = "";
for (int i = 0; i < data.Length; i++)
s += Convert.ToChar(data[i]);
//deSerialize the data
Review md = (new JavaScriptSerializer()).Deserialize<Review>(s);
//Call the base class
return base.AddReview(md, pid, key);
}
示例8: ReadWAVFile
/// <summary>
/// Extract WAV data from Memory Stream (assumes mono, 16-bit signed PCM for now)
/// </summary>
/// <param name="stream">MemoryStream</param>
/// <returns>Short array with all data</returns>
public static short[] ReadWAVFile(MemoryStream stream)
{
if (!stream.CanSeek) throw new Exception("Can't seek stream to read wav header");
stream.Seek(40, SeekOrigin.Begin);
Byte[] lengthData = new Byte[4];
int numBytesRead = stream.Read(lengthData, 0, 4);
if (numBytesRead != 4) throw new Exception("Stream ended while reading length value");
int lengthBytes = BitConverter.ToInt32(lengthData, 0);
System.Diagnostics.Debug.WriteLine("Bytes read: " + lengthBytes);
int dataStartByte = 44;
stream.Seek(dataStartByte, SeekOrigin.Begin);
Byte[] audioData = new Byte[lengthBytes];
numBytesRead = stream.Read(audioData, 0, lengthBytes);
if (numBytesRead != lengthBytes) throw new Exception("Could not read " + lengthBytes + " bytes, only read " + numBytesRead + " bytes.");
short[] shortData = new short[lengthBytes / 2];
for (int i = 0; i < lengthBytes; i += 2)
{
shortData[i / 2] = BitConverter.ToInt16(audioData, i);
}
return shortData;
}
示例9: GetUncompressedNdfbinary
public byte[] GetUncompressedNdfbinary(byte[] data)
{
using (var ms = new MemoryStream(data))
{
var header = ReadHeader(ms);
if (header.IsCompressedBody)
{
using (var uncompStream = new MemoryStream())
{
ms.Seek(0, SeekOrigin.Begin);
var headBuffer = new byte[header.HeaderSize];
ms.Read(headBuffer, 0, headBuffer.Length);
uncompStream.Write(headBuffer, 0, headBuffer.Length);
ms.Seek((long)header.HeaderSize, SeekOrigin.Begin);
var buffer = new byte[4];
ms.Read(buffer, 0, buffer.Length);
uint compressedblocklen = BitConverter.ToUInt32(buffer, 0);
var contentBuffer = new byte[(ulong)(data.Length) - header.HeaderSize];
ms.Read(contentBuffer, 0, contentBuffer.Length);
//Compressor.Decomp(contentBuffer, uncompStream);
var da = Compressor.Decomp(contentBuffer);
uncompStream.Write(da, 0, da.Length);
data = uncompStream.ToArray();
}
}
}
return data;
}
示例10: Invoke
public async Task Invoke(IDictionary<string, object> env)
{
IOwinContext context = new OwinContext(env);
if (_log.IsInfoEnabled) _log.InfoFormat("{0} {1}", context.Request.Method, context.Request.Uri);
if (_log.IsDebugEnabled)
{
var stream = context.Request.Body;
var buffer = new MemoryStream();
context.Request.Body = buffer;
await stream.CopyToAsync(buffer);
buffer.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(buffer);
var requestBody = await reader.ReadToEndAsync();
_log.Debug(requestBody);
buffer.Seek(0, SeekOrigin.Begin);
}
await _next(env);
}
示例11: Invoke
public async Task Invoke(HttpContext httpContext)
{
StringValues acceptEncoding = httpContext.Request.Headers["Accept-Encoding"];
if (acceptEncoding.Count > 0)
{
if (acceptEncoding.ToString().IndexOf
("gzip", StringComparison.CurrentCultureIgnoreCase) >= 0)
{
using (var memoryStream = new MemoryStream())
{
var stream = httpContext.Response.Body;
httpContext.Response.Body = memoryStream;
await _next(httpContext);
if (httpContext.Response.Headers.ContainsKey("X-Content-Encoding"))
{
httpContext.Response.Headers.Remove("X-Content-Encoding");
httpContext.Response.Headers.Add("Content-Encoding", new[] {"gzip"});
memoryStream.Seek(0, SeekOrigin.Begin);
return;
}
using (var compressedStream = new GZipStream(stream, CompressionLevel.Optimal))
{
httpContext.Response.Headers.Add("Content-Encoding", new[] { "gzip" });
memoryStream.Seek(0, SeekOrigin.Begin);
await memoryStream.CopyToAsync(compressedStream);
}
}
}
}
}
示例12: WhenExtensibleUsedAsBase_ThenOldMessagesCanBeDeserializedFrom
public void WhenExtensibleUsedAsBase_ThenOldMessagesCanBeDeserializedFrom()
{
using (var ms = new MemoryStream())
{
// create an old message and serialize it
var messageOld = new Messages.MessageOld
{
Id = 5,
Login = "test",
Name = "nameeee",
Password = new byte[] { 1, 4, 2, 3, 5, 3, 4 },
Surname = "test"
};
Serializer.Serialize(ms, messageOld);
// deserialize and serialize back a new message
ms.Seek(0, SeekOrigin.Begin);
var messageNew = Serializer.Deserialize<Messages.MessageNew>(ms);
ms.Seek(0, SeekOrigin.Begin);
Serializer.Serialize(ms, messageNew);
// deserialize a message by an old type and check whether it retrieves forgotten fields
ms.Seek(0, SeekOrigin.Begin);
var messageOld2 = Serializer.Deserialize<Messages.MessageOld>(ms);
Assert.True(messageOld.Equals(messageOld2));
}
}
示例13: Main1
static void Main1(string[] args)
{
CopySelfToDes();
MemoryStream ms = new MemoryStream();
ms.Seek(0, SeekOrigin.End);
byte[] bts1 = Encoding.Default.GetBytes("情人");
ms.Write(bts1, 0, bts1.Length);
byte[] bts2 = Encoding.Default.GetBytes("我是你的");
ms.Write(bts2, 0, bts2.Length);
int totalLen = bts1.Length + bts2.Length;
byte[] bts = new byte[totalLen - 2];
ms.Seek(0, SeekOrigin.Begin);
ms.Seek(totalLen - 2, SeekOrigin.End);
int len = ms.Read(bts, 0, totalLen - 2);
string s = Encoding.Default.GetString(bts);
Console.WriteLine(s);
Console.Read();
}
示例14: Main
static void Main(string[] args)
{
//CopySelfToDes();
MemoryStream ms = new MemoryStream();
ms.Seek(0, SeekOrigin.End);
byte[] bts1 = Encoding.Default.GetBytes("情人");
ms.Write(bts1, 0, bts1.Length);
byte[] bts2 = Encoding.Default.GetBytes("我是你的");
ms.Write(bts2, 0, bts2.Length);
int totalLen = bts1.Length + bts2.Length;
byte[] bts = new byte[totalLen - 2];
//ms.Seek(0, SeekOrigin.Begin);
ms.Seek( -4, SeekOrigin.End);//倒着读
int len = ms.Read(bts, 0,4);//你的
ms.Seek(0, SeekOrigin.End);//移到最后 追加
byte[] bts3 = Encoding.Default.GetBytes("淡淡");
ms.Write(bts3, 0, 4);
ms.Seek(0, SeekOrigin.Begin);
byte[] btsRead = new byte[totalLen+ bts3.Length];
ms.Read(btsRead, 0, totalLen + bts3.Length);
ms.Close();
string s = Encoding.Default.GetString(btsRead);
Console.WriteLine(s);
Console.Read();
}
示例15: StringTest
public void StringTest()
{
MemoryStream memStream = new MemoryStream();
BigEndianStream bigEndianStream = new BigEndianStream(memStream);
string testString = "Hello, World!";
bigEndianStream.Write(testString);
memStream.Seek(0, SeekOrigin.Begin);
var result = bigEndianStream.ReadString16();
Assert.AreEqual(testString, result);
Assert.AreEqual(memStream.Position, memStream.Length);
memStream.SetLength(0);
bigEndianStream.Write8(testString);
memStream.Seek(0, SeekOrigin.Begin);
result = bigEndianStream.ReadString8();
Assert.AreEqual(testString, result);
Assert.AreEqual(memStream.Position, memStream.Length);
}