本文整理汇总了C#中System.IO.StreamReader.ReadBlock方法的典型用法代码示例。如果您正苦于以下问题:C# StreamReader.ReadBlock方法的具体用法?C# StreamReader.ReadBlock怎么用?C# StreamReader.ReadBlock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.StreamReader
的用法示例。
在下文中一共展示了StreamReader.ReadBlock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Read
/// <summary>
/// Read the data file, skipping over data we're not interested in
/// but parsing and storing the contents of the first data channel
/// </summary>
public static void Read()
{
OriginalValues.Clear();
using (StreamReader r = new StreamReader("ECGSAMPLE.txt"))
{
int bytesRead = 0;
char[] buffer = new char[24];
while (!r.EndOfStream)
{
bytesRead = r.ReadBlock(buffer, 0, 8);
if (bytesRead != 8)
break;
bytesRead = r.ReadBlock(buffer, 0, 24);
if (bytesRead != 24)
break;
else
ParseData(buffer);
bytesRead = r.ReadBlock(buffer, 0, 2);
if (bytesRead != 2)
break;
}
}
return;
}
示例2: Main
static void Main(string[] args)
{
using (StreamReader reader = new StreamReader(@"c:\files\inputFile.txt"))
using (StreamWriter writer = new StreamWriter(@"c:\files\outputFile.txt", false))
{
int position = 0;
while (!reader.EndOfStream)
{
char[] buffer = new char[16];
int charactersRead = reader.ReadBlock(buffer, 0, 16);
writer.Write("{0}: ", String.Format("{0:x4}", position));
position += charactersRead;
for (int i = 0; i < 16; i++)
{
if (i < charactersRead)
{
string hex = String.Format("{0:x2}", (byte)buffer[i]);
writer.Write(hex + " ");
}
else
writer.Write(" ");
if (i == 7) { writer.Write("-- "); }
if (buffer[i] < 32 || buffer[i] > 250) { buffer[i] = '.'; }
}
string bufferContents = new string(buffer);
writer.WriteLine(" " + bufferContents.Substring(0, charactersRead));
}
}
}
示例3: TestManifest
public async Task TestManifest()
{
var stream = new MemoryStream();
var cli = new SpeechClient();
cli.SetStream(stream);
await cli.SendManifest();
stream.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(stream);
var size = Convert.ToInt32(reader.ReadLine());
var outp = new char[size];
reader.ReadBlock(outp, 0, size);
var str = new String(outp);
var re = new Regex(@"^([A-Z_]*)");
Assert.IsTrue(re.Match(str).Value == "APP_MANIFEST");
var jsonstr = str.TrimStart(re.Match(str).Value.ToCharArray());
var jsonstream = new MemoryStream(Encoding.UTF8.GetBytes(jsonstr));
var ser = new DataContractJsonSerializer(typeof(Manifest));
Manifest jsonobj = (Manifest)ser.ReadObject(jsonstream);
Assert.IsTrue(jsonobj.Version == "0.0.1");
Assert.IsTrue(jsonobj.Name == "speech-recognizer");
Assert.IsTrue(jsonobj.DisplayName == "Mycroft Networked Speech Recognizer");
Assert.IsTrue(jsonobj.Description == "Lets applications register speech triggers for Mycroft to look for.");
Assert.IsTrue(jsonobj.InstanceId == "primary");
}
示例4: btn_select_output_click
private void btn_select_output_click(object sender, RoutedEventArgs e)
{
box_eval.Document.Blocks.Clear();
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.InitialDirectory = @"c:\CNTK\nets\";
var result = dlg.ShowDialog();
if (result.HasValue && result.Value)
{
outputFile = dlg.FileName;
lbl_output.Content = dlg.FileName;
}
btn_selectMappingFile.IsEnabled = true;
btn_writeMappings.IsEnabled = true;
var reader = new StreamReader(new FileStream(outputFile, FileMode.Open));
char[] buf = new char[10];
reader.BaseStream.Seek(-10, SeekOrigin.End);
reader.ReadBlock(buf, 0, 10);
string strBuf = new string(buf);
if (strBuf.Contains("mapped"))
{
lbl_mapping.Content = "already mapped";
btn_selectMappingFile.IsEnabled = false;
btn_writeMappings.IsEnabled = false;
}
reader.Close();
}
示例5: FillAdresTable
public void FillAdresTable()
{
string fADRES = this.localPath + "\\" + "ADRES." + ext;
if (File.Exists(fADRES))
{
StreamReader sr = new StreamReader(fADRES, Encoding.GetEncoding(866));
char[] buffer = new char[6400];
while (!sr.EndOfStream)
{
sr.ReadBlock(buffer, 0, 6400);
Address sAdres = new Address();
//sAdres = &buffer;
OrganizationDataSet.AdresTableRow newrow = this.dataset.AdresTable.NewAdresTableRow();
int tna = (int)buffer[1];
tna = tna << 4;
tna &= (int)buffer[0];
newrow.tna = tna;
this.dataset.AdresTable.AddAdresTableRow(newrow);
}
sr.Close();
}
else
System.Windows.Forms.MessageBox.Show("Сбой при открытии ADRES", "ADRES");
}
示例6: Decode
internal static SourceText Decode(Stream stream, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
{
stream.Seek(0, SeekOrigin.Begin);
long longLength = stream.Length;
if (longLength == 0)
{
return SourceText.From(string.Empty, encoding, checksumAlgorithm);
}
var maxCharRemainingGuess = encoding.GetMaxCharCountOrThrowIfHuge(stream);
Debug.Assert(longLength > 0 && longLength <= int.MaxValue); // GetMaxCharCountOrThrowIfHuge should have thrown.
int length = (int)longLength;
using (var reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: Math.Min(length, 4096), leaveOpen: true))
{
ArrayBuilder<char[]> chunks = ArrayBuilder<char[]>.GetInstance(1 + maxCharRemainingGuess / ChunkSize);
while (!reader.EndOfStream)
{
var nextChunkSize = ChunkSize;
if (maxCharRemainingGuess < ChunkSize)
{
// maxCharRemainingGuess typically overestimates a little
// so we will first fill a slightly smaller (maxCharRemainingGuess - 64) chunk
// and then use 64 char tail, which is likley to be resized.
nextChunkSize = Math.Max(maxCharRemainingGuess - 64, 64);
}
char[] chunk = new char[nextChunkSize];
int charsRead = reader.ReadBlock(chunk, 0, chunk.Length);
if (charsRead == 0)
{
break;
}
maxCharRemainingGuess -= charsRead;
if (charsRead < chunk.Length)
{
Array.Resize(ref chunk, charsRead);
}
// Check for binary files
if (throwIfBinaryDetected && IsBinary(chunk))
{
throw new InvalidDataException();
}
chunks.Add(chunk);
}
// We must compute the checksum and embedded text blob now while we still have the original bytes in hand.
// We cannot re-encode to obtain checksum and blob as the encoding is not guaranteed to round-trip.
var checksum = CalculateChecksum(stream, checksumAlgorithm);
var embeddedTextBlob = canBeEmbedded ? EmbeddedText.CreateBlob(stream) : default(ImmutableArray<byte>);
return new LargeText(chunks.ToImmutableAndFree(), reader.CurrentEncoding, checksum, checksumAlgorithm, embeddedTextBlob);
}
}
示例7: parse
public static NamedTag parse(StreamReader sr, TagType type)
{
var name = "";
//read the name length
var buffer = new char[2];
sr.ReadBlock(buffer, 0, 2);
var bytebuf = new byte[] {(byte) buffer[1], (byte) buffer[0]};
short length = BitConverter.ToInt16(bytebuf, 0);
buffer = new char[length];
sr.ReadBlock(buffer, 0, length);
name = new string(buffer);
Type t = GetClrTypeForTag(type);
return (NamedTag)Activator.CreateInstance(t, sr, name, type);
}
示例8: ConvertStandartToRegions
public static void ConvertStandartToRegions(string fnameIn, string fnameOut)
{
var fin = new StreamReader(fnameIn);
var fout = new StreamWriter(fnameOut);
const int bufferSize = 5000;
var buff = new char[bufferSize];
string residual = "";
string lastPerson = "";
var adjacentRegions = new List<string>();
while(!fin.EndOfStream)
{
fin.ReadBlock(buff, 0, bufferSize);
var buffer = new string(buff);
var strs = new List<string>();
if(residual != "" && residual[residual.Length - 1] == ']')
strs.Add(residual);
strs.AddRange(buffer.Split(new[] { ';', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries));
if(residual != "" && residual[residual.Length - 1] != ']')
strs[0] = residual + strs[0];
residual = strs.Last();
string bufferOut = "";
for(int i = 0; i < strs.Count - 1; i++)
{
string[] edge = strs[i].Split(new[] { ' ', '-', '>' }, StringSplitOptions.RemoveEmptyEntries);
if(edge.Count() != 3 || edge[2][3] == '4')
continue;
if(edge[0][0] == 'f')
{
bufferOut += edge[0] + " -> " + edge[1] + " " + "1\r\n";
}
if(edge[0][0] == 'p')
{
if(lastPerson != edge[0])
{
for(var regIn = 0; regIn < adjacentRegions.Count; regIn++)
for(var regOut = regIn + 1; regOut < adjacentRegions.Count; regOut++)
{
bufferOut += adjacentRegions[regIn] + " -> " + adjacentRegions[regOut] + " " + 1.0 / (adjacentRegions.Count - 1.0) + "\r\n";
bufferOut += adjacentRegions[regOut] + " -> " + adjacentRegions[regIn] + " " + 1.0 / (adjacentRegions.Count - 1.0) + "\r\n";
}
adjacentRegions = new List<string>();
}
adjacentRegions.Add(edge[1]);
}
lastPerson = edge[0];
}
fout.Write(bufferOut);
}
fin.Close();
fout.Close();
}
示例9: Read
public override void Read(StreamReader reader)
{
base.Read(reader);
// Line ending
var buffer = new char[2];
var read = reader.ReadBlock(buffer, 0, buffer.Length);
if (read != 2 || buffer != "\r\n".ToArray())
throw new LeituraException("Final de linha não encontrado.");
}
示例10: Main
static void Main(string[] args)
{
const byte INPUT_FILENAME = 0;
const byte OUTPUT_FILENAME = 1;
CharacterFrequency[] characterArray = new CharacterFrequency[256];
for (int i = 0; i < 256; i++)
{
characterArray[i] = new CharacterFrequency((char)i);
characterArray[i].setCharacter((char)i);
}
if (args.Length != 2)
{
Console.WriteLine("Usage: CommandLine [input filename] [output file name]");
Environment.Exit(0);
}
Console.WriteLine("The input filename is: {0}", args[INPUT_FILENAME]);
Console.WriteLine("The output filename is: {0}", args[OUTPUT_FILENAME]);
using (StreamReader SR = new StreamReader(args[INPUT_FILENAME]))
{
int read;
FileInfo file = new FileInfo(args[INPUT_FILENAME]);
long fileLength = file.Length;
int f = Convert.ToInt32(fileLength);
string path = File.ReadAllText(args[INPUT_FILENAME]);
// Step 1
char[] block = new char[1024];
for (int k = 0; k < (f/1024); k++)
{
// Step 2
read = SR.ReadBlock(block, 0, block.Length);
// Step 3
for (int i = 0; i < read; i++)
{
characterArray[(block[i])].increment();
}
}
// Step 4
string text;
int Cfrequency=0;
for (int i = 0; i < characterArray.Length; i++)
{
text = ((("") + (char)i + ("(") + i.ToString()) + (")") + " " + characterArray[i].getFrequency(Cfrequency).ToString() + Environment.NewLine);
File.AppendAllText(args[OUTPUT_FILENAME], text, Encoding.UTF8);
}
}
}
示例11: Grab
List<Show> Grab(GrabParametersBase p,ILogger logger)
{
var pp = (CyfraPlus.GrabParameters)p;
var shows = new List<Show>();
var wr = WebRequest.Create(string.Format(urlFormat, pp.Date.ToString(DateFormat)));
logger.WriteEntry(string.Format("Grabbing Cyfra+ date {0} ...", pp.Date.ToString(DateFormat)), LogType.Info);
var res = (HttpWebResponse)wr.GetResponse();
const int ChannelDepth = 2;
using (var sr = new StreamReader(res.GetResponseStream()))
{
var startDownloadTime = DateTime.Now;
var data = new StringBuilder();
int blockSize = 16384;
while (!sr.EndOfStream)
{
var buf = new char[blockSize];
var totalRead = sr.ReadBlock(buf, 0, blockSize);
data.Append(buf);
if (DateTime.Now - startDownloadTime > TimeSpan.FromSeconds(1))
{
startDownloadTime = DateTime.Now;
logger.WriteEntry(string.Format("Downloaded {0:#,##0} bytes so far", data.Length), LogType.Info);
}
}
var r = new Newtonsoft.Json.JsonTextReader(new StringReader(data.ToString()));
while (r.Read())
{
r.Read();
var channelNumber = r.ReadAsInt32();
var channelName = r.ReadAsString();
r.Read();
r.Read();
while (r.Depth > ChannelDepth)
{
var show = new Show();
show.Channel = channelName.Trim();
var programId = r.ReadAsInt32();
show.Title = Tools.CleanupText(r.ReadAsString());
show.StartTime = new DateTime(1970, 1, 1).Add(TimeSpan.FromSeconds(r.ReadAsInt32().Value));
show.EndTime = show.StartTime.Add(TimeSpan.FromSeconds(Convert.ToDouble(r.ReadAsInt32())));
var num = r.ReadAsInt32();
shows.Add(show);
var depth = r.Depth;
while (r.Depth == depth)
r.Read();
r.Read();
}
}
}
return shows;
}
示例12: AddFile
public override void AddFile(String path, Stream data)
{
String adjustedPath = GetFullPath(path);
String dir = Path.GetDirectoryName(adjustedPath);
if(Directory.Exists(dir) == false)
Directory.CreateDirectory(dir);
FileStream fs = new FileStream(adjustedPath, FileMode.Create);
//byte[] bytes = HttpFunction.ReadFromStream(data,8192);
StreamReader sreader = new StreamReader (data);
char[] bytes = new char[8192];
int bytesread = sreader.ReadBlock (bytes, 0, 8192);
while(bytesread > 0) {
fs.Write (System.Text.Encoding.Default.GetBytes(bytes,0,bytesread), 0, bytesread);
bytesread = sreader.ReadBlock (bytes, 0, 8192);
}
sreader.Close ();
fs.Close ();
}
示例13: Decode
internal static SourceText Decode(Stream stream, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected)
{
stream.Seek(0, SeekOrigin.Begin);
int length = (int)stream.Length;
if (length == 0)
{
return SourceText.From(string.Empty, encoding, checksumAlgorithm);
}
var maxCharRemainingGuess = encoding.GetMaxCharCount(length);
using (var reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: Math.Min(length, 4096), leaveOpen: true))
{
ArrayBuilder<char[]> chunks = ArrayBuilder<char[]>.GetInstance(1 + maxCharRemainingGuess / ChunkSize);
while (!reader.EndOfStream)
{
var nextChunkSize = ChunkSize;
if (maxCharRemainingGuess < ChunkSize)
{
// maxCharRemainingGuess typically overestimates a little
// so we will first fill a slightly smaller (maxCharRemainingGuess - 64) chunk
// and then use 64 char tail, which is likley to be resized.
nextChunkSize = Math.Max(maxCharRemainingGuess - 64, 64);
}
char[] chunk = new char[nextChunkSize];
int charsRead = reader.ReadBlock(chunk, 0, chunk.Length);
if (charsRead == 0)
{
break;
}
maxCharRemainingGuess -= charsRead;
if (charsRead < chunk.Length)
{
Array.Resize(ref chunk, charsRead);
}
// Check for binary files
if (throwIfBinaryDetected && IsBinary(chunk))
{
throw new InvalidDataException();
}
chunks.Add(chunk);
}
var checksum = CalculateChecksum(stream, checksumAlgorithm);
return new LargeText(chunks.ToImmutableAndFree(), reader.CurrentEncoding, checksum, checksumAlgorithm);
}
}
示例14: Tail
//public IObservable<string> TailV2(IFile file)
//{
// return ObservableFile.WatchLines(file.GetNativePath(), Encoding.Default);
//}
public IObservable<string> Tail(IFile file, IScheduler scheduler = null)
{
return Observable.Create<string>(subj =>
{
var disposable = new CompositeDisposable();
scheduler = scheduler ?? RxApp.TaskpoolScheduler;
var abortSignal = new ManualResetEvent(false);
disposable.Add(Disposable.Create(() => abortSignal.Set()));
disposable.Add(scheduler.Schedule(abortSignal, (sched, state) =>
{
using (var reader = new StreamReader(
file.GetContent().OpenStream(FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
{
long lastOffset = reader.BaseStream.Length;
if (reader.BaseStream.Length > 0)
{
// Send the last 10 kb of text to the reader.
lastOffset = Math.Max(0, reader.BaseStream.Length - (1024 * 10));
}
while (!state.WaitOne(100))
{
// Idle if file hasn't changed.
if (reader.BaseStream.Length <= lastOffset)
{
if (reader.BaseStream.Length < lastOffset)
{
lastOffset = reader.BaseStream.Length;
}
continue;
}
// Read the data.
reader.BaseStream.Seek(lastOffset, SeekOrigin.Begin);
var delta = reader.BaseStream.Length - lastOffset;
var buffer = new char[delta];
reader.ReadBlock(buffer, 0, buffer.Length);
// Publish the data.
subj.OnNext(new string(buffer));
// Update the offset.
lastOffset = reader.BaseStream.Position;
}
}
return Disposable.Empty;
}));
return disposable;
});
}
示例15: KekeMethod
public void KekeMethod()
{
string url = parseReturns.Text.Substring( parseReturns.Text.IndexOf( "http://" ) );
int n = url.IndexOf( ' ' );
if ( n != -1 )
url = url.Substring( 0, n );
HttpWebRequest htp = null;
try {
htp = (HttpWebRequest)WebRequest.Create( url );
}
catch (UriFormatException) {
returns = new string[] {
BoldNickReturn( parseReturns.User.Nickname, parseReturns.Channel.Name, "Bad URL."),
};
return;
}
HttpWebResponse htpr = null;
try {
htpr = (HttpWebResponse)htp.GetResponse();
}
catch {
returns = new string[] {
BoldNickReturn( parseReturns.User.Nickname, parseReturns.Channel.Name, "HTTP Request not completed."),
};
return;
}
StreamReader res = new StreamReader(htpr.GetResponseStream());
char[] buf = new char[1024];
int x = 0;
string title = null;
ASCIIEncoding ae = new ASCIIEncoding();
StringBuilder sb = new StringBuilder();
while ( ( x = res.ReadBlock( buf, 0, 1024 ) ) > 0 ) {
string s = sb.Append( buf ).ToString();
int starttag = s.IndexOf( "<title>" );
if ( starttag == -1 )
continue;
s = s.Substring( starttag + 7 );
title = s.Substring( 0, s.IndexOf( "</title>" ) );
title = title.Trim();//title.Trim( '\r', '\n', '\t' );
}
res.Close();
if ( title != null ) {
returns = new string[] { BoldNickReturn( parseReturns.User.Nickname, parseReturns.Channel.Name, title) , };
}
else returns = null;
}