本文整理汇总了C#中System.IO.BufferedStream.Seek方法的典型用法代码示例。如果您正苦于以下问题:C# BufferedStream.Seek方法的具体用法?C# BufferedStream.Seek怎么用?C# BufferedStream.Seek使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.BufferedStream
的用法示例。
在下文中一共展示了BufferedStream.Seek方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Download
/// <summary>
/// 分块下载
/// </summary>
/// <param name="bufferedStream"></param>
/// <param name="startPos"></param>
/// <param name="endPos"></param>
/// <param name="localFilePath"></param>
/// <param name="bucketName"></param>
/// <param name="fileKey"></param>
private static void Download(BufferedStream bufferedStream, long startPos, long endPos, String localFilePath, String bucketName, String fileKey)
{
Stream contentStream = null;
try
{
var getObjectRequest = new GetObjectRequest(bucketName, fileKey);
getObjectRequest.SetRange(startPos, endPos);
var ossObject = client.GetObject(getObjectRequest);
byte[] buffer = new byte[1024 * 1024];
var bytesRead = 0;
bufferedStream.Seek(startPos, SeekOrigin.Begin);
contentStream = ossObject.Content;
while ((bytesRead = contentStream.Read(buffer, 0, buffer.Length)) > 0)
{
bufferedStream.Write(buffer, 0, bytesRead);
}
}
finally
{
if (contentStream != null)
{
contentStream.Dispose();
}
}
}
示例2: ComputeHashes
public static HashData ComputeHashes(string fileName)
{
try
{
using (FileStream stream = File.OpenRead(fileName))
{
using (var bufferedStream = new BufferedStream(stream, 1024 * 32))
{
string md5, sha1, sha256;
byte[] checksum;
using (var md5Cng = new MD5Cng())
{
checksum = md5Cng.ComputeHash(bufferedStream);
md5 = BitConverter.ToString(checksum).Replace("-", string.Empty);
}
stream.Seek(0, SeekOrigin.Begin);
bufferedStream.Seek(0, SeekOrigin.Begin);
using (var sha1Cng = new SHA1Cng())
{
checksum = sha1Cng.ComputeHash(bufferedStream);
sha1 = BitConverter.ToString(checksum).Replace("-", string.Empty);
}
stream.Seek(0, SeekOrigin.Begin);
bufferedStream.Seek(0, SeekOrigin.Begin);
using (var sha256Cng = new SHA256Cng())
{
checksum = sha256Cng.ComputeHash(bufferedStream);
sha256 = BitConverter.ToString(checksum).Replace("-", string.Empty);
}
return new HashData(md5, sha1, sha256);
}
}
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return null;
}
示例3: CreateReportXAML
/// <summary>
/// Creates the report.
/// </summary>
public string CreateReportXAML(string serverUrl, ReportConfig config)
{
if (config.StaticXAMLReport != null)
return config.StaticXAMLReport;
// load the xslt template
System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform();
try {
LoadTemplate(xslt, serverUrl, config.ReportGroup, config.ReportTemplate);
}
catch (System.Exception) {
throw new ScrumFactory.Exceptions.ScrumFactoryException("Error_reading_report_template");
}
// creates a buffer stream to write the report context in XML
System.IO.BufferedStream xmlBuffer = new System.IO.BufferedStream(new System.IO.MemoryStream());
System.Xml.XmlWriterSettings writerSettings = new System.Xml.XmlWriterSettings();
writerSettings.CheckCharacters = false;
writerSettings.OmitXmlDeclaration = true;
System.Xml.XmlWriter reportDataStream = System.Xml.XmlWriter.Create(xmlBuffer, writerSettings);
// write XML start tag
reportDataStream.WriteStartDocument();
reportDataStream.WriteStartElement("ReportData");
// create report context in XML
CreateDefaultXMLContext(reportDataStream, writerSettings, serverUrl, config);
// finish XML document
reportDataStream.WriteEndDocument();
reportDataStream.Flush();
xmlBuffer.Seek(0, System.IO.SeekOrigin.Begin);
// debug
//System.IO.StreamReader s = new System.IO.StreamReader(xmlBuffer);
//string ss = s.ReadToEnd();
System.Xml.XmlReaderSettings readerSettings = new System.Xml.XmlReaderSettings();
readerSettings.CheckCharacters = false;
System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(xmlBuffer, readerSettings);
// creates a buffer stream to write the XAML flow document
System.IO.StringWriter xamlBuffer = new System.IO.StringWriter();
System.Xml.XmlWriter xamlWriter = System.Xml.XmlWriter.Create(xamlBuffer, writerSettings);
// creates the flow document XMAL
xslt.Transform(xmlReader, xamlWriter);
// sets the flow document at the view
return xamlBuffer.ToString();
}
示例4: Main
public static void Main(string[] args)
{
string filename =
//"compl.bit";
//"01-Lovecraft_s Death.mp3";
//"01-enochian_crescent-tatan.mp3";
//"bad-info-crc.mp3";
//"test-id3v1.mp3";
//"test-id3v2.mp3";
"test-lame.mp3";
Stream mp3Stream =
new BufferedStream(
new FileStream(
filename,
FileMode.Open,
FileAccess.Read));
Mp3Validator validator = new Mp3Validator();
validator.OnValidationFailure += ValidationFailureEventHandler;
validator.Validate(mp3Stream);
Console.WriteLine("Done");
mp3Stream.Seek(0, SeekOrigin.Begin);
Mp3StreamReader reader = new Mp3StreamReader(mp3Stream);
foreach (IMp3StreamRegion region in reader)
{
}
Console.WriteLine("Done");
mp3Stream.Seek(0, SeekOrigin.Begin);
while (-1 != mp3Stream.ReadByte())
{
}
Console.WriteLine("Done");
Console.ReadKey();
}
示例5: avi_start
/* start writing an AVI file */
public void avi_start(string filename)
{
avi_close();
fd = new BufferedStream(File.Open(filename, FileMode.Create));
fd.Seek(224, SeekOrigin.Begin);
nframes = 0;
totalsize = 0;
max_buff_size = 0;
lista_tams = new List<u32>();
start_timestamp = DateTime.Now.Ticks;
}
示例6: avi_start
/* start writing an AVI file */
public void avi_start(string filename)
{
avi_close();
fd = new BufferedStream(File.Open(filename, FileMode.Create));
fd.Seek(2048,SeekOrigin.Begin);
nframes = 0;
totalsize = 0;
}
示例7: PutBinary
/// <summary>Put as binary, i.e. read and write raw bytes.</summary>
/// <remarks>
/// The stream is closed after the transfer is complete if
/// <see cref="CloseStreamsAfterTransfer"/> is <c>true</c> (the default) and are left
/// open otherwise.
/// </remarks>
/// <param name="srcStream">Input stream of data to put.</param>
/// <param name="remoteFile">Name of remote file in current directory.</param>
/// <param name="append"><c>true</c> if appending, <c>false</c> otherwise</param>
/// <param name="alwaysCloseStreams"><c>true if a local file is being put</c></param>
/// <returns>Number of bytes transferred.</returns>
private long PutBinary(Stream srcStream, string remoteFile, bool append, bool alwaysCloseStreams)
{
BufferedStream input = null;
BufferedStream output = null;
Exception storedEx = null;
lastBytesTransferred = 0;
try
{
input = new BufferedStream(srcStream);
InitPut(remoteFile, append);
// get an output stream
output = new BufferedStream(GetOutputStream());
// if resuming, we skip over the unwanted bytes
if (resume && resumeMarker > 0)
{
input.Seek(resumeMarker, SeekOrigin.Current);
}
else
resumeMarker = 0;
byte[] buf = new byte[transferBufferSize];
// read a chunk at a time and write to the data socket
long monitorCount = 0;
int count = 0;
DateTime start = DateTime.Now;
if (throttler != null)
{
throttler.Reset();
}
while ((count = input.Read(buf, 0, buf.Length)) > 0 && !cancelTransfer)
{
output.Write(buf, 0, count);
lastBytesTransferred += count;
monitorCount += count;
if (throttler != null)
{
throttler.ThrottleTransfer(lastBytesTransferred);
}
if (BytesTransferred != null && !cancelTransfer && monitorCount >= monitorInterval)
{
BytesTransferred(this, new BytesTransferredEventArgs(remoteFile, lastBytesTransferred, resumeMarker));
monitorCount = 0;
}
start = SendServerWakeup(start);
}
}
catch (Exception ex)
{
log.Error("Caught exception " + ex.Message);
storedEx = ex;
}
finally
{
resume = false;
resumeMarker = 0;
try
{
if ((alwaysCloseStreams || closeStreamsAfterTransfer))
{
log.Debug("Closing source stream");
if (input != null)
input.Close();
}
}
catch (SystemException ex)
{
log.Warn("Caught exception closing stream", ex);
}
try
{
if (output!=null)
output.Flush();
}
catch (SystemException ex)
{
log.Warn("Caught exception flushing output-stream", ex);
}
CloseDataSocket(output);
// if we did get an exception bail out now
if (storedEx != null)
//.........这里部分代码省略.........
示例8: Load
// ReSharper restore UnusedMember.Local
private bool Load(ILoadMonitor loader)
{
ProgressStatus status =
new ProgressStatus(string.Format(Resources.BiblioSpecLibrary_Load_Loading__0__library,
Path.GetFileName(FilePath)));
loader.UpdateProgress(status);
long lenRead = 0;
// AdlerChecksum checksum = new AdlerChecksum();
try
{
// Use a buffered stream for initial read
BufferedStream stream = new BufferedStream(CreateStream(loader), 32 * 1024);
int countHeader = (int) LibHeaders.count*4;
byte[] libHeader = new byte[countHeader];
if (stream.Read(libHeader, 0, countHeader) != countHeader)
throw new InvalidDataException(Resources.BiblioSpecLibrary_Load_Data_truncation_in_library_header_File_may_be_corrupted);
lenRead += countHeader;
// Check the first byte of the primary version number to determine
// whether the format is little- or big-endian. Little-endian will
// have the version number in this byte, while big-endian will have zero.
if (libHeader[(int) LibHeaders.version1 * 4] == 0)
_bigEndian = true;
int numSpectra = GetInt32(libHeader, (int) LibHeaders.num_spectra);
var dictLibrary = new Dictionary<LibKey, BiblioSpectrumInfo>(numSpectra);
var setSequences = new HashSet<LibSeqKey>();
string revStr = string.Format("{0}.{1}", // Not L10N
GetInt32(libHeader, (int) LibHeaders.version1),
GetInt32(libHeader, (int) LibHeaders.version2));
Revision = float.Parse(revStr, CultureInfo.InvariantCulture);
// checksum.MakeForBuff(libHeader, AdlerChecksum.ADLER_START);
countHeader = (int) SpectrumHeaders.count*4;
byte[] specHeader = new byte[1024];
byte[] specSequence = new byte[1024];
for (int i = 0; i < numSpectra; i++)
{
int percent = i * 100 / numSpectra;
if (status.PercentComplete != percent)
{
// Check for cancellation after each integer change in percent loaded.
if (loader.IsCanceled)
{
loader.UpdateProgress(status.Cancel());
return false;
}
// If not cancelled, update progress.
loader.UpdateProgress(status = status.ChangePercentComplete(percent));
}
// Read spectrum header
int bytesRead = stream.Read(specHeader, 0, countHeader);
if (bytesRead != countHeader)
throw new InvalidDataException(Resources.BiblioSpecLibrary_Load_Data_truncation_in_spectrum_header_File_may_be_corrupted);
// If this is the first header, and the sequence length is zero,
// then this is a Linux format library. Switch to linux format,
// and start over.
if (i == 0 && GetInt32(specHeader, (int)SpectrumHeaders.seq_len) == 0)
{
_linuxFormat = true;
stream.Seek(lenRead, SeekOrigin.Begin);
// Re-ead spectrum header
countHeader = (int)SpectrumHeadersLinux.count * 4;
bytesRead = stream.Read(specHeader, 0, countHeader);
if (bytesRead != countHeader)
throw new InvalidDataException(Resources.BiblioSpecLibrary_Load_Data_truncation_in_spectrum_header_File_may_be_corrupted);
}
lenRead += bytesRead;
// checksum.MakeForBuff(specHeader, checksum.ChecksumValue);
int charge = GetInt32(specHeader, (int)SpectrumHeaders.charge);
if (charge > TransitionGroup.MAX_PRECURSOR_CHARGE)
throw new InvalidDataException(Resources.BiblioSpecLibrary_Load_Invalid_precursor_charge_found_File_may_be_corrupted);
int numPeaks = GetInt32(specHeader, (int)SpectrumHeaders.num_peaks);
int seqLength = GetInt32(specHeader, (_linuxFormat ?
(int)SpectrumHeadersLinux.seq_len : (int)SpectrumHeaders.seq_len));
int copies = GetInt32(specHeader, (_linuxFormat ?
(int)SpectrumHeadersLinux.copies : (int)SpectrumHeaders.copies));
// Read sequence information
int countSeq = (seqLength + 1)*2;
if (stream.Read(specSequence, 0, countSeq) != countSeq)
throw new InvalidDataException(Resources.BiblioSpecLibrary_Load_Data_truncation_in_spectrum_sequence_File_may_be_corrupted);
lenRead += countSeq;
// checksum.MakeForBuff(specSequence, checksum.ChecksumValue);
//.........这里部分代码省略.........
示例9: SeekOnUnseekableStream_Throws_NotSupportedException
public static void SeekOnUnseekableStream_Throws_NotSupportedException()
{
using (WrappedMemoryStream underlying = new WrappedMemoryStream(true, true, false))
using (BufferedStream stream = new BufferedStream(underlying))
{
Assert.Throws<NotSupportedException>(() => stream.Seek(0, new SeekOrigin()));
}
}
示例10: With_WebSocket_FailsWithDoubleMessageAwait
public void With_WebSocket_FailsWithDoubleMessageAwait()
{
var handshake = GenerateSimpleHandshake();
using (var ms = new BufferedStream(new MemoryStream()))
using (WebSocket ws = new WebSocketRfc6455(ms, new WebSocketListenerOptions() { PingTimeout = Timeout.InfiniteTimeSpan }, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1), new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2), handshake.Request, handshake.Response, handshake.NegotiatedMessageExtensions))
{
ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8);
ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
ws.ReadMessage();
ws.ReadMessage();
}
}
示例11: writeURL
//.........这里部分代码省略.........
RSS.RSSImage oRSSImage = new RSS.RSSImage(HTTPServer.Settings.HTTP_URL + "/images/RSS_Logo_YAPS.png", HTTPServer.Settings.HTTP_URL, "YAPS VCR");
RSS.RSSRoot oRSSRoot = new RSS.RSSRoot(oRSSChannel,oRSSImage, XMLStream);
RSS.RSSItem oRSSItem = null;
// now go for a walk with all the Recordings...
#region Sort the Recordings Listing
List<Recording> sortedDoneRecordingList;
lock (HTTPServer.vcr_scheduler.doneRecordings.SyncRoot)
{
// TODO: add ascending/descending setting + reimplement the sorting algorithm
sortedDoneRecordingList = Sorter.SortRecordingTable(HTTPServer.vcr_scheduler.doneRecordings, false);
}
#endregion
// TODO: maybe we can do this without foreach...faster; but because this is not critical function of YAPS...well low priority
foreach (Recording recording in sortedDoneRecordingList)
{
oRSSItem = new RSS.RSSItem(recording.Recording_Name, HTTPServer.Settings.HTTP_URL + "/" + recording.Recording_ID.ToString());
oRSSItem.PubDate = recording.StartsAt.ToString();
oRSSItem.Comment = recording.Comment;
// generate Category List for this recording
oRSSItem.Categories = HTTPServer.vcr_scheduler.Category_Processor.RenderCategoryLine(HTTPServer.vcr_scheduler.Category_Processor.AutomaticCategoriesForRecording(recording), ',');
oRSSRoot.Items.Add(oRSSItem);
}
RSS.RSSUtilities.PublishRSS(oRSSRoot);
XMLStream.Seek(0, SeekOrigin.Begin);
byte[] byteArray = new byte[XMLStream.Length];
int xmlcount = XMLStream.Read(byteArray, 0, Convert.ToInt32(XMLStream.Length));
writeSuccess(xmlcount,"text/xml");
ns.Write(byteArray, 0, xmlcount);
ns.Flush();
XMLStream.Close();
}
#endregion
#endregion
}
else
if (url.StartsWith("/dvb/"))
{
#region Streaming Request
#region CheckAuthentification
if (!HTTPAuthProcessor.AllowedToAccessLiveStream(AC_endpoint.Address))
{
// now give the user a 403 and break...
writeForbidden();
ns.Flush();
return;
}
#endregion
// check if there is a MulticastProcessor Object for this channel
VCRandStreaming HReq = new VCRandStreaming(false,null,HTTPServer);
示例12: Seek
public void Seek ()
{
BufferedStream stream = new BufferedStream (mem);
stream.Write (new byte [] {0, 1, 2, 3, 4, 5}, 0, 6);
Assert.AreEqual (6, stream.Position, "test#01");
stream.Seek (-5, SeekOrigin.End);
Assert.AreEqual (1, stream.Position, "test#02");
stream.Seek (3, SeekOrigin.Current);
Assert.AreEqual (4, stream.Position, "test#03");
stream.Seek (300, SeekOrigin.Current);
Assert.AreEqual (304, stream.Position, "test#04");
}
示例13: Seek_ClosedMemoryStream
public void Seek_ClosedMemoryStream ()
{
MemoryStream ms = new MemoryStream ();
BufferedStream stream = new BufferedStream (ms);
ms.Close ();
stream.Seek (0, SeekOrigin.Begin);
}
示例14: PutBinary
/// <summary>
/// Put as binary, i.e. read and write raw bytes
/// </summary>
/// <param name="srcStream"> input stream of data to put
/// </param>
/// <param name="remoteFile"> name of remote file we are writing to
/// </param>
/// <param name="append"> true if appending, false otherwise
/// </param>
private void PutBinary(Stream srcStream, string remoteFile, bool append)
{
BufferedStream input = null;
BinaryWriter output = null;
SystemException storedEx = null;
long size = 0;
try
{
input = new BufferedStream(srcStream);
InitPut(remoteFile, append);
// get an output stream
output = new BinaryWriter(data.DataStream);
// if resuming, we skip over the unwanted bytes
if (resume)
{
input.Seek(resumeMarker, SeekOrigin.Current);
}
byte[] buf = new byte[transferBufferSize];
if (TransferStarted != null)
TransferStarted(this, new EventArgs());
// read a chunk at a time and write to the data socket
long monitorCount = 0;
int count = 0;
while ((count = input.Read(buf, 0, buf.Length)) > 0 && !cancelTransfer)
{
output.Write(buf, 0, count);
size += count;
monitorCount += count;
if (BytesTransferred != null && monitorCount > monitorInterval)
{
BytesTransferred(this, new BytesTransferredEventArgs(size));
monitorCount = 0;
}
}
}
catch (SystemException ex)
{
storedEx = ex;
}
finally
{
resume = false;
try
{
if (input != null)
input.Close();
}
catch (SystemException ex)
{
log.Warn("Caught exception closing stream", ex);
}
try
{
if (output != null)
output.Close();
}
catch (SystemException ex)
{
log.Warn("Caught exception closing data socket", ex);
}
// if we did get an exception bail out now
if (storedEx != null)
throw storedEx;
// notify the final transfer size
if (BytesTransferred != null)
BytesTransferred(this, new BytesTransferredEventArgs(size));
if (TransferComplete != null)
TransferComplete(this, new EventArgs());
// log bytes transferred
log.Debug("Transferred " + size + " bytes to remote host");
}
}
示例15: Read
public void Read ()
{
mem.Write (new byte [] {0, 1, 2, 3, 4, 5, 6, 7}, 0, 8);
BufferedStream stream = new BufferedStream (mem);
byte [] bytes = new byte [10];
stream.Read (bytes, 0, 3);
Assert.AreEqual (0, bytes [0], "test#01");
Assert.AreEqual (0, bytes [1], "test#02");
Assert.AreEqual (0, bytes [2], "test#03");
stream.Seek (0, SeekOrigin.Begin);
stream.Read (bytes, 0, 3);
Assert.AreEqual (0, bytes [0], "test#04");
Assert.AreEqual (1, bytes [1], "test#05");
Assert.AreEqual (2, bytes [2], "test#06");
Assert.AreEqual (0, bytes [0], "test#07");
stream.Read (bytes, 5, 3);
Assert.AreEqual (3, bytes [5], "test#08");
Assert.AreEqual (4, bytes [6], "test#09");
Assert.AreEqual (5, bytes [7], "test#10");
Assert.AreEqual (0, bytes [8], "test#11");
stream.Read (bytes, 0, 10);
Assert.AreEqual (3, bytes [5], "test#12");
Assert.AreEqual (4, bytes [6], "test#13");
Assert.AreEqual (5, bytes [7], "test#14");
Assert.AreEqual (0, bytes [9], "test#15");
}