/// <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; }
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"); }
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"); }
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)); } } }
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(); }
public void ReadFile(int index) { string path = "test.txt"; System.IO.StreamReader file = new System.IO.StreamReader(path); char[] buffer = new char[100]; try { file.ReadBlock(buffer, index, buffer.Length); } catch (System.IO.IOException e) { Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message); } finally { foreach (var c in buffer) { Console.Write(c); } if (file != null) { file.Close(); } } Console.ReadKey(); }
internal static string ReadAsMany(this System.IO.StreamReader stream, int bytesToRead) { var buffer = new char[bytesToRead]; stream.ReadBlock(buffer, 0, bytesToRead); return(new string(buffer)); }
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); } }
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); }
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(); }
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."); }
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; }
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); } } }
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); } }
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 (); }
//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; }); }
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; }
/// <summary> /// 使用StreamReader.ReadBlock()方法 /// </summary> /// <param name="reader"></param> public static void DisplayResultStringByUsingReadBlock(System.IO.StreamReader reader) { char[] charBuffer = new char[10]; string result = string.Empty; reader.ReadBlock(charBuffer, 0, 10); for (int i = 0; i < charBuffer.Length; i++) { result += charBuffer[i]; } Console.WriteLine("使用StreamReader.ReadBlock()方法得到Text文件中前10个数据为 : {0}", result); }
static void Main(string[] args) { bool GoodOpen = false; try { System.IO.FileStream fs = new System.IO.FileStream(@"pi-billion.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.Read); StreamReader sr = new StreamReader(fs); char[] b = new char[1000001537]; sr.ReadBlock(b, 0, 1000001537); GoodOpen = true; } catch (Exception) { Console.WriteLine("error opening \"pi-billion.txt\""); } while (GoodOpen) { Console.WriteLine("Enter the date in the format DDMMYY"); string strRead = Console.ReadLine(); List<char> BuffList = new List<char>(); for (int i = 0; i < strRead.Length; i++) { BuffList.Add(strRead[i]); } string BuffString = ""; for (int i = 0; i < BuffList.Count; i++) { BuffString += Convert.ToString(BuffList[i]); } decimal BuffLong = Convert.ToDecimal(BuffString); for (long i = 2; i < 1000001537; i++) { string str = ""; for (long j = i; j < i + BuffList.Count; j++) { str += Convert.ToString(b[j]); } decimal strLong = Convert.ToDecimal(str); if (strLong == BuffLong) { Console.WriteLine(i - 1); break; } else if (i == 1000001536) { Console.WriteLine("No matches found"); } } System.Threading.Thread.Sleep(2000); } }
void OpenFile() { if (openFileDialog.ShowDialog() == DialogResult.OK) { // Stream and Stream Reader were also likely candidates. // They allow opening of existing files, as well as read access from them. Stream file = openFileDialog.OpenFile(); StreamReader reader = new StreamReader(file); char[] text = new char[file.Length]; reader.ReadBlock(text, 0, (int)file.Length); textEditor.Text = new String(text); reader.Close(); } }
public void LerArquivo(String Path) { int Index = 0; FileInfo fi = new FileInfo(Path); System.IO.StreamReader Arquivo = new System.IO.StreamReader(Path); char[] Buffer = new char[fi.Length]; Arquivo.ReadBlock(Buffer, Index, Buffer.Length); String str = new string(Buffer); Console.WriteLine(str); Console.WriteLine(fi.Length); Arquivo.Close(); }
private string GetJsonPart(Stream stream) { stream.Seek(JsonBegin, SeekOrigin.Begin); const int searchStringLength = 6; using (var streamReader = new StreamReader(stream)) { var buffer = new char[searchStringLength]; int charsCount = 0; bool jsonEndIsFound = false; while (!streamReader.EndOfStream) { streamReader.ReadBlock(buffer, 0, searchStringLength); if (new string(buffer).Equals("}}star")) { jsonEndIsFound = true; break; } streamReader.BaseStream.Seek(JsonBegin + charsCount, SeekOrigin.Begin); charsCount++; streamReader.DiscardBufferedData(); } if (!jsonEndIsFound) { throw new NotSupportedException(); } stream.Seek(JsonBegin, SeekOrigin.Begin); var bytesLengths = (charsCount * 2); var jsonBytes = new byte[bytesLengths]; stream.Read(jsonBytes, 0, bytesLengths); var str = Encoding.UTF8.GetString(jsonBytes); return str.Substring(0, str.LastIndexOf("}}star", StringComparison.InvariantCulture) + 2); } }
private string FindTo(StreamReader reader, long startPos, long endPos) { long pos = FindStringInStream(reader, "<To>", startPos, endPos); if (pos == -1) return string.Empty; reader.BaseStream.Seek(pos, SeekOrigin.Begin); reader.DiscardBufferedData(); char[] buffer = new char[4096]; int charsRead = reader.ReadBlock(buffer, 0, buffer.Length); string str = new string(buffer, 0, charsRead); Match m = Regex.Match(str, @".*?<To>(.*?)(</).*", RegexOptions.IgnoreCase); if (m != null && m.Success) { return m.Groups[1].Value; } return string.Empty; }
// Create a DrawingVisual that contains a bitmap. public DrawingVisual DrawMonoBitmap(Point location, Size size, string filename, Pen pen) { DrawingVisual drawingVisual = new DrawingVisual(); // Retrieve the DrawingContext in order to create new drawing content. DrawingContext drawingContext = drawingVisual.RenderOpen(); int bitmapSize = (int)(size.Height * size.Width) / 8; char[] chardata = new char[bitmapSize * 2]; int readCount = 0; // Create a stream reader object to read a text file. using (var reader = new System.IO.StreamReader(filename)) { readCount = reader.ReadBlock(chardata, 0, bitmapSize * 2); } byte[] data = new byte[readCount]; for (int i = 0; i < readCount; i++) { data[i] = (byte)chardata[i]; } BitmapImage biImg = new BitmapImage(); MemoryStream ms = new MemoryStream(data); biImg.BeginInit(); biImg.StreamSource = ms; biImg.EndInit(); ImageSource imgSrc = biImg as ImageSource; // Create a rectangle and draw it in the DrawingContext. Rect rect = new Rect(location, size); drawingContext.DrawImage(imgSrc, rect); // Persist the drawing content. drawingContext.Close(); this.children.Add(drawingVisual); return(drawingVisual); }
public IStaticGatewayHandler GetGatewayHandler(IContext objContext) { using (System.IO.Stream stream = Assembly.GetExecutingAssembly() .GetManifestResourceStream("Bronze.Controls.VWG.OtherResources.PIE.htc")) using (StreamReader reader = new StreamReader(stream)) { char[] objBuffer = new char[stream.Length]; reader.ReadBlock(objBuffer, 0, (int)stream.Length); objContext.HttpContext.Response.Expires = 60*24*370; objContext.HttpContext.Response.Cache.SetExpires(DateTime.Now.AddYears(1)); objContext.HttpContext.Response.Cache.SetCacheability(System.Web.HttpCacheability.Public); objContext.HttpContext.Response.ContentType = "text/x-component"; objContext.HttpContext.Response.Write(objBuffer, 0, objBuffer.Length); objContext.HttpContext.Response.Flush(); } return null; }
private void LoadStreamBuffer() { Match m1 = Regex.Match(this.text, @"stream\s*"); this.streamStartOffset = m1.Index + m1.Value.Length; this.streamLength = this.length - this.streamStartOffset; this.streamBuffer = new byte[this.streamLength]; this.PdfFile.memory.Seek(this.address+this.streamStartOffset, SeekOrigin.Begin); this.PdfFile.memory.Read(this.streamBuffer, 0,this.streamLength); this.PdfFile.memory.Seek(this.address,SeekOrigin.Begin); StreamReader sr = new StreamReader(this.PdfFile.memory); char[] startChars = new char[this.streamStartOffset]; sr.ReadBlock(startChars, 0, this.streamStartOffset); StringBuilder sb = new StringBuilder(); sb.Append(startChars); this.text = sb.ToString(); }
public void Parse(StreamReader reader) { if (Token != null) { reader.BaseStream.Seek(Token.Length, SeekOrigin.Current); } int longestTokenLength = 0; foreach (TokenParserBase token in PossibleNextToken) { if (token.Token != null) { longestTokenLength = Math.Max(longestTokenLength, token.Token.Length); } } char[] buffer = new char[longestTokenLength]; reader.ReadBlock(buffer, 0, longestTokenLength); reader.BaseStream.Seek(-longestTokenLength, SeekOrigin.Current); foreach (TokenParserBase token in PossibleNextToken) { if (token.Token == null) continue; bool success = true; for (int i=0;i<token.Token.Length; ++i) { char tc = token.Token[i]; char c = buffer[i]; if (Char.ToUpperInvariant(tc) != Char.ToUpperInvariant(c)) { success = false; break; } } if (success) { token.Parse(reader); } } }
private void loadP5(System.IO.StreamReader f) { pixels = new pixel[mdata.totalpixels]; char[] buffer = new char[mdata.totalpixels]; f.ReadBlock(buffer, 0, mdata.totalpixels); for (int i = 0; i < mdata.totalpixels; i++) { pixels[i].value = Convert.ToByte(buffer[i]); pixels[i].id = i; pixels[i].selected = false; pixels[i].found = false; } mdata.buffersize = buffer.Length; Console.WriteLine(mdata.buffersize); }
private void themdata(string p) { using (var input=new StreamReader("t.txt")) using (var output=new StreamWriter("t.txt.tep",true,Encoding.UTF8)) { var buf= new char[4096]; int read = 0; output.WriteLine(p); do { read = input.ReadBlock(buf, 0, buf.Length); output.Write(buf, 0, read); } while (read>0); output.Flush(); output.Close(); input.Close(); } File.Replace("t.txt.tep", "t.txt", "t.txt.back"); File.Delete("t.txt.back"); }
public static int CountLines(string path) { int lines = 0; char[] buffer = new char[4096]; using (StreamReader reader = new StreamReader(path)) { while (!reader.EndOfStream) { reader.ReadBlock(buffer, 0, buffer.Length); for (int i = 0; i < buffer.Length; i++) { if (buffer[i] == '\n') lines++; } } } return lines; }
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); } using (var reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: Math.Min(length, 4096), leaveOpen: true)) { ArrayBuilder<char[]> chunks = ArrayBuilder<char[]>.GetInstance(1 + length / ChunkSize); while (!reader.EndOfStream) { char[] chunk = new char[ChunkSize]; int charsRead = reader.ReadBlock(chunk, 0, ChunkSize); if (charsRead == 0) { break; } if (charsRead < ChunkSize) { 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); } }
private string FindMethod(StreamReader reader, long startPos, long endPos) { long pos = FindStringInStream(reader, "Body", startPos, endPos); if (pos == -1) return string.Empty; reader.BaseStream.Seek(pos, SeekOrigin.Begin); reader.DiscardBufferedData(); char[] buffer = new char[200]; int charsRead = reader.ReadBlock(buffer, 0, buffer.Length); string str = new string(buffer, 0, charsRead); Match m = Regex.Match(str, @".*?<(.*?)( |>).*", RegexOptions.IgnoreCase); if (m != null && m.Success) { string method = m.Groups[1].Value; if (method.Contains(":")) { method = method.Split(':')[1]; } return method; } return string.Empty; }
public void Given_a_hash_checksum_transcoder_When_written_to_the_transcoder_Then_the_inner_stream_contains_the_written_data_followed_by_its_hash() { var hashAlgorithm = SHA256.Create(); var streamHashGenerator = new CryptoStreamHashGenerator(hashAlgorithm); var hashChecksumTranscodingStreamFactory = new HashChecksumTranscodingStreamFactory(streamHashGenerator); const int HashByteCount = 32; const string TestText = "Test"; using (var innerStream = new MemoryStream()) using (var hashChecksumTranscodingStream = hashChecksumTranscodingStreamFactory.CreateTrancodingStream(innerStream)) { var writer = new StreamWriter(hashChecksumTranscodingStream); writer.Write(TestText); writer.Flush(); hashChecksumTranscodingStream.Flush(); innerStream.Position = 0; var reader = new StreamReader(innerStream); var stringBuffer = new char[4]; reader.ReadBlock(stringBuffer, 0, 4); var expectedInnerStreamLength = TestText.Length + HashByteCount; Assert.AreEqual(expectedInnerStreamLength, innerStream.Length); const string ExpectedString = TestText; var actualString = new string(stringBuffer); Assert.AreEqual(ExpectedString, actualString); const string ExpectedHash = "53-2E-AA-BD-95-74-88-0D-BF-76-B9-B8-CC-00-83-2C-20-A6-EC-11-3D-68-22-99-55-0D-7A-6E-0F-34-5E-25"; innerStream.Position = 4; var hashBuffer = new byte[innerStream.Length - innerStream.Position]; innerStream.Read(hashBuffer, 0, HashByteCount); var actualHash = BitConverter.ToString(hashBuffer); Assert.AreEqual(ExpectedHash, actualHash); } }
public string GetNext(string mobileNumber) { var sub = subscriptions.SingleOrDefault(s => s.Number == mobileNumber); if(sub == null) { throw new ArgumentException("Subscription not found for mobile number: " + mobileNumber); } var buffer = new char[PAGE_SIZE]; using (var stream = GetStream(sub.BookId)) using (var reader = new StreamReader(stream)) { stream.Seek(sub.Index, SeekOrigin.Begin); reader.ReadBlock(buffer, 0, PAGE_SIZE); } sub.Index += PAGE_SIZE; return new string(buffer); }
public void WriteOneRecord() { MARCWriter writer = new MARCWriter("onerecord.dat"); foreach (MARCRecord record in oneRecord) { writer.Write(record); } writer.Close(); StreamReader answer = new StreamReader(@"C:\Documents and Settings\wkurt\My Documents\Visual Studio 2008\Projects\TestMARC\TestMARC\one.dat"); StreamReader result = new StreamReader("onerecord.dat"); char[] answerBuffer = new char[1]; char[] resultBuffer = new char[1]; while(answer.Peek() != -1 && result.Peek() != -1) { answer.ReadBlock(answerBuffer,0,1); result.ReadBlock(resultBuffer,0,1); Assert.Equals(answerBuffer[0],resultBuffer[0]); } }
public static bool Check() { string cpuid = MachineInfo.GetCPUID(); char[] crcInfo = CRC32.GetCRC32(cpuid).ToCharArray(); char[] licenseInfo = new char[8]; string licenseFile = HttpContext.Current.Server.MapPath("~/App_Data/erp_license.lic"); if (!File.Exists(licenseFile)) { return false; } StreamReader sr = new StreamReader(licenseFile); sr.ReadBlock(licenseInfo, 0, 8); sr.Close(); for (int i = 0; i < 8; i++) { if (crcInfo[i] != licenseInfo[i]) return false; } return true; }
protected void FillBuff() { int i; if (maxNextCharInd == 4096) { maxNextCharInd = nextCharInd = 0; } try { if (((i = inputStream.ReadBlock(nextCharBuf, maxNextCharInd, 4096 - maxNextCharInd)) == 0) && ((4096 - maxNextCharInd) > 0)) { inputStream.Close(); throw new System.IO.IOException(); } else { maxNextCharInd += i; } return; } catch (System.IO.IOException e) { if (bufpos != 0) { --bufpos; backup(0); } else { bufline[bufpos] = line; bufcolumn[bufpos] = column; } throw e; } }
private bool readBCI2000dat(string filename, out Data_BCI2000 info, out double[][] samples) { FileStream dataStream = null; StreamReader dataReader = null; // check if the file exists if (!File.Exists(filename)) { MessageBox.Show("Could not find input file", "File error", MessageBoxButtons.OK, MessageBoxIcon.Error); info = null; samples = null; return(false); } try { // open file stream dataStream = new FileStream(filename, FileMode.Open); // open reader //dataReader = new System.IO.StreamReader(filestream, System.Text.Encoding.UTF8, true, 128); dataReader = new System.IO.StreamReader(dataStream); } catch (Exception) { // message MessageBox.Show("Could not create filestream to data file '" + filename + "' for reading"); info = null; samples = null; return(false); } // create a new bci2000 data object info = new Data_BCI2000(); // retrieve the first line info.firstLine = dataReader.ReadLine(); // retrieve HeaderLen string fieldName = "HeaderLen="; int fieldValueLength = 6; int pos = info.firstLine.IndexOf(fieldName); if (pos == -1 || info.firstLine.Length < pos + fieldName.Length + fieldValueLength) { MessageBox.Show("Could not retrieve " + fieldName + ", aborting"); info = null; samples = null; return(false); } bool result = Int32.TryParse(info.firstLine.Substring(pos + fieldName.Length, fieldValueLength), out info.headerLen); if (!result) { MessageBox.Show("Could not retrieve " + fieldName + ", aborting"); info = null; samples = null; return(false); } // retrieve SourceCh fieldName = "SourceCh="; fieldValueLength = 2; pos = info.firstLine.IndexOf(fieldName); if (pos == -1 || info.firstLine.Length < pos + fieldName.Length + fieldValueLength) { MessageBox.Show("Could not retrieve " + fieldName + ", aborting"); info = null; samples = null; return(false); } result = Int32.TryParse(info.firstLine.Substring(pos + fieldName.Length, fieldValueLength), out info.sourceCh); if (!result) { MessageBox.Show("Could not retrieve " + fieldName + ", aborting"); info = null; samples = null; return(false); } // retrieve StatevectorLen fieldName = "StatevectorLen="; //fieldValueLength = 3; pos = info.firstLine.IndexOf(fieldName); fieldValueLength = Math.Min(3, info.firstLine.Length - (pos + fieldName.Length)); // adjusted: fieldValueLength is variable: so it is either three, or in case the string is shorter, the remainder of the string: either 1 or 2 if (pos == -1 || info.firstLine.Length < pos + fieldName.Length + fieldValueLength) { MessageBox.Show("Could not retrieve " + fieldName + ", aborting"); info = null; samples = null; return(false); } result = Int32.TryParse(info.firstLine.Substring(pos + fieldName.Length, fieldValueLength), out info.stateVectorLen); if (!result) { MessageBox.Show("Could not retrieve " + fieldName + ", aborting"); info = null; samples = null; return(false); } // retrieve entire header char[] buffer = new char[info.headerLen]; dataStream.Position = 0; dataReader.DiscardBufferedData(); dataReader.ReadBlock(buffer, 0, info.headerLen); info.header = new string(buffer); // retrieve the sample rate from the header if (!getDoubleParameterFromHeader(info.header, "SamplingRate", out info.samplingRate)) { MessageBox.Show("Could not retrieve sample rate from header, aborting"); info = null; samples = null; return(false); } // set the dataStream position to the start of the data (needed, readblock before messed it up) dataStream.Position = info.headerLen; // set int mDataSize = 2; // each sample in BCI2000 is stored as an int16 (2 bytes) // calculate the number of samples info.numSamples = (int)(dataStream.Length - info.headerLen) / (mDataSize * info.sourceCh + info.stateVectorLen); // init matrix for all samples values samples = new double[info.numSamples][]; // retrieve the data for (int i = 0; i < info.numSamples; i++) { // init the row of samples samples[i] = new double[info.sourceCh]; // read the samples byte[] channels = new byte[mDataSize * info.sourceCh]; dataStream.Read(channels, 0, mDataSize * info.sourceCh); // convert each channel for (int j = 0; j < info.sourceCh; j++) { samples[i][j] = BitConverter.ToInt16(channels, j * mDataSize); } // read the state vector data byte[] stateVector = new byte[info.stateVectorLen]; dataStream.Read(stateVector, 0, info.stateVectorLen); // TODO: interpret state vector } // close the datastream if (dataStream != null) { dataStream.Close(); } dataReader = null; dataStream = null; // return success return(true); }
public void ImportLayoutDotFitFile(int numWorkouts, string pathToLayoutFit) { char[] charBuf = new char[32]; lines.Clear(); sFs.Clear(); bFs.Clear(); System.IO.StreamReader objFile = null; objFile = new System.IO.StreamReader(pathToLayoutFit); for (int ii = 0; ii < numWorkouts; ii++) { objFile.ReadBlock(charBuf, 0, 32); lines.Add(new LayoutLine(charBuf)); if (ii == 0) { //determine workoutLength string layoutDirectory = pathToLayoutFit.Substring(0, pathToLayoutFit.Length - 10); workoutLength = getWorkoutLength(layoutDirectory + lines[ii].binaryFitFileName + ".fit"); } bFs.Add(new BinaryFit(lines[ii].binaryFitFileName, workoutLength)); sFs.Add(new SoundFit(lines[ii].soundFitFileName)); //okay, at this point we now have the LayoutFit object constructed //along with some empty BinaryFit and SoundFit objects //now we need to populate the BinaryFit and SoundFit objects with //valid information from the files on the disk //first we need to fill in the command blocks for this newly created //BinaryFit file BinaryFit bF = bFs[ii]; SoundFit sF = sFs[ii]; string bFName = new string(charBuf, 0, 8); string sFName = new string(charBuf, 9, 8); if (bFName.Equals("********")) //nothing to read from disk here { ASCIIEncoding AE = new ASCIIEncoding(); byte[] me = new byte[1]; //byte me :> :P :) ;) me[0] = lowByte((short)ii); me[0] += 65; //'A' string bFNamer = string.Format("W000000{0}", new String(AE.GetChars(me))); string sFNamer = string.Format("S000000{0}", new String(AE.GetChars(me))); bFs[ii] = new BinaryFit(bFNamer, workoutLength); sFs[ii] = new SoundFit(sFNamer); Replace(ii, new LayoutLine(bFNamer, sFNamer)); } else //each BinaryFit object can load itself from disk { string sFPath = pathToLayoutFit; sFPath = sFPath.Replace("layout", sFName); sF.LoadFromDisk(sFPath); string bFPath = pathToLayoutFit; bFPath = bFPath.Replace("layout", bFName); bF.LoadFromDisk(bFPath, sF); } } }
private void button2_Click(object sender, EventArgs e) ///write to pic---------------------------------------------------- { // System.IO.StreamReader LogReader = new System.IO.StreamReader("D:log.txt"); System.IO.StreamReader LogReader = new System.IO.StreamReader("E:log.txt"); // string LogLine; int charcount; char[] temp = new char[81]; // char TempLOGVal; // LogLine = LogReader.ReadToEnd(); Lcount = 0; do { /* t=0; * do * { * temp[t++] = (char)LogLine[charcount]; * } while ((LogLine[charcount] != 0x0A) && (LogLine[charcount-1] != 0x0D)); * charcount++; */ charcount = LogReader.ReadBlock(temp, 0, 72); //charcount = LogReader.Read(); // LogLine = LogReader.ReadLine(); if (charcount == 0x0000) { SendBuffer[0] = (byte)0xFF; hSp.Write(SendBuffer, 0, 1); MessageBox.Show("Writing Process Complet"); break; } t = 0; do { SendBuffer[t] = (byte)temp[t]; // byte length t++; } while (t < 70); //SendBuffer[70] = (byte)0x0D; Send_Data: hSp.Write(SendBuffer, 0, 70); count = 0; wait: count++; /*if (count >= 1000000) * { * MessageBox.Show("Communication With the Device Have the Error"); * button2.Enabled = false; * break; * }*/ if (ACKSTATUS == 0) { goto wait; } ACKSTATUS = 0; if (ReciveAck == 0xFF) { goto Send_Data; } // Linecount++; // progressBar1.Value = 5*Lcount/2; Lcount++; progressBar1.Value = 3 + Lcount; } while (line != null); LogReader.Close(); Application.Exit(); }
static void Main(string[] args) { string corpus_path = args[0]; string classes_path = args[1]; string result_path = args[2]; Dictionary <string, int> word2freq = new Dictionary <string, int>(); using (System.IO.StreamReader rdr = System.IO.File.OpenText(corpus_path)) { int BUF_SIZE = 16384; char[] buffer = new char[BUF_SIZE]; string prev_token_head = null; while (rdr.EndOfStream == false) { int nchar = rdr.ReadBlock(buffer, 0, BUF_SIZE); if (nchar < 0) { break; } string[] words = new string( buffer ).Split(' '); if (!string.IsNullOrEmpty(prev_token_head) && words.Length > 0) { words[0] = prev_token_head + words[0]; } int nword = words.Length; if (buffer[BUF_SIZE - 1] != ' ') { nword--; prev_token_head = words[words.Length - 1]; } for (int i = 0; i < nword; ++i) { if (words[i].Length > 0) { int freq; if (word2freq.TryGetValue(words[i], out freq)) { word2freq[words[i]] = freq + 1; } else { word2freq.Add(words[i], 1); } } } } } Dictionary <int, List <string> > class2words = new Dictionary <int, List <string> >(); using (System.IO.StreamReader rdr = new System.IO.StreamReader(classes_path)) { while (!rdr.EndOfStream) { string line = rdr.ReadLine(); if (line == null) { break; } string[] toks = line.Split(' '); string word = toks[0]; int class_index = int.Parse(toks[1]); List <string> words; if (!class2words.TryGetValue(class_index, out words)) { words = new List <string>(); class2words.Add(class_index, words); } words.Add(word); } } using (System.IO.StreamWriter wrt = new System.IO.StreamWriter(result_path)) { // foreach( var p in class2words.OrderBy( z => z.Key ) ) foreach (var p in class2words.OrderByDescending(z => z.Value.Select(q => word2freq.ContainsKey(q) ? word2freq[q] : 0).Sum())) { wrt.Write("{0}\t", p.Key); wrt.Write("{0}", string.Join(" ", p.Value.Where(z => word2freq.ContainsKey(z)).OrderByDescending(z => word2freq[z]).ToArray())); wrt.WriteLine(""); } } return; }