Read() public method

public Read ( ) : int
return int
        /// <summary>
        /// post方法传递json数据
        /// </summary>
        /// <param name="urlStr">目标url</param>
        /// <param name="urlStrFunc">对应方法</param>
        /// <param name="urlStrPara">json参数</param>
        /// <returns></returns>
        public static string Post_RSA_Json(string urlStr, string urlStrFunc, string urlStrPara)
        {
            Encoding encode = Encoding.UTF8;
            byte[] arrB = encode.GetBytes(urlStrPara);
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(urlStr + urlStrFunc);
            myReq.Method = "POST";
            myReq.ContentType = "application/x-www-form-urlencoded";
            myReq.ContentLength = arrB.Length;
            Stream outStream = myReq.GetRequestStream();
            outStream.Write(arrB, 0, arrB.Length);
            outStream.Close();
            //接收HTTP做出的响应
            WebResponse myResp = myReq.GetResponse();

            Stream ReceiveStream = myResp.GetResponseStream();
            StreamReader readStream = new StreamReader(ReceiveStream, encode);
            Char[] read = new Char[256];
            int count = readStream.Read(read, 0, 256);
            string str = null;
            while (count > 0)
            {
                str += new String(read, 0, count);
                count = readStream.Read(read, 0, 256);
            }
            readStream.Close();
            myResp.Close();
            return str;
        }
Example #2
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string memo = "";
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.cmono.net/?post=504");

                HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                Stream receiveStream = myHttpWebResponse.GetResponseStream();
                Encoding encode = Encoding.GetEncoding("utf-8");
                StreamReader sr = new StreamReader(receiveStream, encode);
                char[] read  = new char[256];
                int count = sr.Read(read, 0, 256);
                while (count>0)
                {
                    string str = new string(read, 0, count);
                    memo += str;
                    count = sr.Read(read, 0, 256);

                }
                sr.Close();
                myHttpWebResponse.Close();
                this.textBox1.Text = memo;
                Regex reg = new Regex(@"<div.+class=context?>(?<content>.+?)</div>", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                string val = reg.Match(memo).Groups["content"].Value;
                MessageBox.Show(val);

            }
            catch (Exception ex)
            {

            }
        }
Example #3
0
        /// <summary>
        /// 将Stream 转化成 string
        /// </summary>
        /// <param name="stream">流</param>
        public static string ConvertToString(Stream stream)
        {
            #region

            string strResult = "";
            StreamReader sr = new StreamReader(stream, Encoding.UTF8);

            Char[] read = new Char[256];
            // Read 256 charcters at a time.
            int count = sr.Read(read, 0, 256);

            while (count > 0)
            {
                // Dump the 256 characters on a string and display the string onto the console.
                string str = new String(read, 0, count);
                strResult += str;
                count = sr.Read(read, 0, 256);
            }

            // 释放资源
            sr.Close();
            //sr.Dispose();
            return strResult;

            #endregion
        }
 /// <summary>
 /// Helper class to persist BizTalk message bodies
 /// </summary>
 /// <param name='message'>The BizTalk message to persist</param>
 /// <param name='destination'>The destination directory to persist the file to</param>
 public static void PersistMessage(IBaseMessage message, string destination)
 {
     using (var fs = new FileStream(destination, FileMode.Create))
     {
         var enc = Encoding.GetEncoding("UTF-8");
         if (!string.IsNullOrEmpty(message.BodyPart.Charset))
         {
             enc = Encoding.GetEncoding(message.BodyPart.Charset);
         }
         using (var writer = new StreamWriter(fs, enc))
         {
             var msgStream = message.BodyPart.GetOriginalDataStream();
             using (var reader = new StreamReader(msgStream, enc))
             {
                 const int size = 1024;
                 var buf = new char[size];
                 var charsRead = reader.Read(buf, 0, size);
                 while (charsRead > 0)
                 {
                     writer.Write(buf, 0, charsRead);
                     charsRead = reader.Read(buf, 0, size);
                 }
             }
         }
     }
 }
Example #5
0
        static void Main()
        {
            using (StreamReader reader = new StreamReader(@"..\..\XML.txt"))
            {
                int i = reader.Read();
                while (i != -1)
                {
                    if (i == '>')
                    {
                        string text = String.Empty;

                        while ((i = reader.Read()) != -1 && i != '<')
                        {
                            text += (char)i;
                        }

                        if (!String.IsNullOrWhiteSpace(text))
                        {
                            Console.WriteLine(text.Trim());
                        }
                    }
                    i = reader.Read();
                }

            }
        }
Example #6
0
        /// <summary>
        /// Check an ASCII encoded file for the presence of bad characters
        /// and character combinations.  What we consider bad:
        ///  - Tab characters.
        ///  - Carraige returns not followed by a line feed.
        ///  - Line feeds not preceeded by a carraige return.
        /// </summary>
        /// <param name="sourcePath">File to check.</param>
        /// <returns>True if no bad characters found.  False otherwise.</returns>
        public static bool CheckSourceFileForBadCharacters(string sourcePath)
        {
            const int HT = 0x09;  // Horizontal tab.
            const int LF = 0x0a;  // Line feed.
            const int CR = 0x0d;  // Carraige return.

            using (StreamReader reader = new StreamReader(sourcePath))
            {
                int octet;

                // REVIEW: Sanity check reader.CurrentEncoding here?
                while ((octet = reader.Read()) > 0)
                {
                    switch (octet)
                    {
                        case CR:
                            if (reader.Read() != LF)
                            {
                                return false;
                            }

                            break;

                        case LF:
                        case HT:
                            return false;
                    }
                }
            }

            return true;
        }
Example #7
0
        public static String ProcessDigit(int FirstCharactor, StreamReader DataStream)
        {
            StringBuilder theNumber = new StringBuilder();
            theNumber.Append((char)FirstCharactor);
            int peekedChar;
            //43 + 45 - 46 .
            while (((peekedChar = DataStream.Peek()) >= 48 && peekedChar <= 57)
                || peekedChar == 46)
            {
                theNumber.Append((char)DataStream.Read());
            }

            if (peekedChar == 69) // E
            {
                theNumber.Append((char)DataStream.Read());
                if ((peekedChar = DataStream.Peek()) == 43 || peekedChar == 45)
                {
                    theNumber.Append((char)DataStream.Read());
                }
                while ((peekedChar = DataStream.Peek()) >= 48 && peekedChar <= 57)
                {
                    theNumber.Append((char)DataStream.Read());
                }
            }
            return theNumber.ToString();
            //Console.WriteLine(theNumber);
        }
 /// <summary>
 /// Outputs the HTTP reponse to the console
 /// 
 /// Code taken from http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.getresponsestream.aspx
 /// </summary>
 /// <param name="response"></param>       
 private static void displayHttpWebReponse(HttpWebResponse response)
 {
     Console.WriteLine(response.StatusCode);
     Stream receiveStream = response.GetResponseStream();
     Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
     // Pipes the stream to a higher level stream reader with the required encoding format.
     StreamReader readStream = new StreamReader(receiveStream, encode);
     Console.WriteLine("\r\nResponse stream received.");
     Char[] read = new Char[256];
     // Reads 256 characters at a time.
     int count = readStream.Read(read, 0, 256);
     Console.WriteLine("HTML...\r\n");
     while (count > 0)
     {
         // Dumps the 256 characters on a string and displays the string to the console.
         String str = new String(read, 0, count);
         Console.Write(str);
         count = readStream.Read(read, 0, 256);
     }
     Console.WriteLine("");
     // Releases the resources of the response.
     response.Close();
     // Releases the resources of the Stream.
     readStream.Close();
 }
Example #9
0
        public INode Parse(StreamReader reader)
        {
            HtmlToken token = ConsumeTagToken(reader);
            if (token == HtmlToken.OpenMetaTag)
            {
                CommentParser commentParser = new CommentParser();
                string comment = commentParser.ParseCommentText(reader);
            }
            else if (token == HtmlToken.OpenComment)
            {
                CommentParser commentParser = new CommentParser();
                string comment = commentParser.ParseCommentText(reader);
            }
            else if (token == HtmlToken.OpenTag)
            {
                ConsumeTagName(reader);
            }

            int c = reader.Read();
            while (c > -1)
            {
                if (c == '>')
                {
                }
                c = reader.Read();
            }
            return null;
        }
Example #10
0
        public static string GetPage(string url,int tryTimes = 1)
        {
            string content = "";
            try
            {
                HttpWebRequest myHttpWebRequest1 = (HttpWebRequest)WebRequest.Create(url);
                myHttpWebRequest1.KeepAlive = false;
                HttpWebResponse myHttpWebResponse1;

                myHttpWebResponse1 = (HttpWebResponse)myHttpWebRequest1.GetResponse();
                System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
                Stream streamResponse = myHttpWebResponse1.GetResponseStream();
                StreamReader streamRead = new StreamReader(streamResponse, utf8);
                Char[] readBuff = new Char[256];
                int count = streamRead.Read(readBuff, 0, 256);
                while (count > 0)
                {
                    String outputData = new String(readBuff, 0, count);
                    content += outputData;
                    count = streamRead.Read(readBuff, 0, 256);
                }
                myHttpWebResponse1.Close();
            }
            catch
            {
                tryTimes++;
                if (tryTimes <= 3)
                    content = GetPage(url, tryTimes);
            }
            return (content);
        }
Example #11
0
        public static List<string> ReadFile(string filename)
        {
            List<string> listFileContent = new List<string>();

            StringBuilder stringBuilder = new StringBuilder();
            using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader streamReader = new StreamReader(fileStream))
                {
                    char[] fileContents = new char[_bufferSize];
                    int charsRead = streamReader.Read(fileContents, 0, _bufferSize);

                    // Can't do much with 0 bytes
                    //if (charsRead == 0)
                    //    throw new Exception("File is 0 bytes");

                    while (charsRead > 0)
                    {
                        stringBuilder.Append(fileContents);
                        charsRead = streamReader.Read(fileContents, 0, _bufferSize);
                    }

                    string[] contentArray = stringBuilder.ToString().Split(new char[] { '\r', '\n' });
                    foreach (string line in contentArray)
                    {
                        listFileContent.Add(line.Replace("#", ""));
                    }
                    listFileContent.RemoveAll(s => string.IsNullOrEmpty(s));
                }
            }
            return listFileContent;
        }
 private void parseGrilles()
 {
     string line;
     StreamReader file = new StreamReader(pathFile);
     while ((line = file.ReadLine()) != null)
     {
         string nom = file.ReadLine();
         string date = file.ReadLine();
         string symboles = file.ReadLine();
         int longueur = symboles.Length;
         Grille grille = new Grille(nom, date, symboles, longueur);
         for (int i = 0; i < longueur; i++)
         {
             grille.Cases[i] = new Case[longueur];
             for (int j = 0; j < longueur; j++)
             {
                 grille.Cases[i][j] = new Case();
                 grille.Cases[i][j].Valeur = (char)file.Read();
                 grille.Cases[i][j].Row = i;
                 grille.Cases[i][j].Column = j;
             }
             char tabulation = (char)file.Read();
             char sautDeLigne = (char)file.Read();
         }
         if ((grille.Longueur == 9 || grille.Longueur == 16 || grille.Longueur == 25) && grille.EstValide())
         {
             grilles.Add(grille);
         }
     }
     file.Close();
 }
        public static Dictionary<string, object> ParseValues(StreamReader reader, Dictionary<string, object> values)
        {
            char ch;

            do
            {
                do
                {
                    ch = (char)reader.Read();
                } while (whitespace.Contains(ch));

                if (ch == '"')
                {
                    string key = parseString(reader);
                    do
                    {
                        ch = (char)reader.Read();
                    } while (whitespace.Contains(ch));

                    if (ch == '"')
                    {
                        values.Add(key, parseString(reader));
                    }
                    else if (ch == '{')
                    {
                        values.Add(key, ParseValues(reader, new Dictionary<string, object>()));
                    }
                }
            }  while (ch != '}' && !reader.EndOfStream);

            return values;
        }
Example #14
0
 private static string POST(string Url, string Data)
 {
     WebRequest req = WebRequest.Create(Url);
     req.Method = "POST";
     req.Timeout = 100000;
     req.ContentType = "application/x-www-form-urlencoded";
     byte[] sentData = Encoding.GetEncoding(1251).GetBytes(Data);
     req.ContentLength = sentData.Length;
     Stream sendStream = req.GetRequestStream();
     sendStream.Write(sentData, 0, sentData.Length);
     sendStream.Close();
     WebResponse res = req.GetResponse();
     Stream ReceiveStream = res.GetResponseStream();
     StreamReader sr = new StreamReader(ReceiveStream, Encoding.UTF8);
     //Кодировка указывается в зависимости от кодировки ответа сервера
     Char[] read = new Char[256];
     int count = sr.Read(read, 0, 256);
     string Out = String.Empty;
     while (count > 0)
     {
         String str = new String(read, 0, count);
         Out += str;
         count = sr.Read(read, 0, 256);
     }
     return Out;
 }
        public static string PostModel(string url, string param, Encoding encoding,int timeout)
        {
            Encoding encode = encoding;
            byte[] arrB = encode.GetBytes(param);
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
            if (timeout > 0) myReq.Timeout = timeout;
            myReq.Method = "POST";
            myReq.ContentType = "application/x-www-form-urlencoded";
            myReq.ContentLength = arrB.Length;
            Stream outStream = myReq.GetRequestStream();
            outStream.Write(arrB, 0, arrB.Length);
            outStream.Close();
            WebResponse myResp = null;
            try
            {
                myResp = myReq.GetResponse();
            }
            catch
            {

            }
            Stream ReceiveStream = myResp.GetResponseStream();
            StreamReader readStream = new StreamReader(ReceiveStream, encode);
            Char[] read = new Char[256];
            int count = readStream.Read(read, 0, 256);
            string str = null;
            while (count > 0)
            {
                str += new String(read, 0, count);
                count = readStream.Read(read, 0, 256);
            }
            readStream.Close();
            myResp.Close();
            return str;
        }
Example #16
0
        public void ParseStream(StreamReader reader)
        {
            _length = null; // basically an 'isDirty' flag

            //this is a 'trigram' model so just hard code first two characters
            if (reader.EndOfStream) return; // too short == no trigrams
            char first = (char)reader.Read();

            if (reader.EndOfStream) return;
            char second = (char)reader.Read(); // too short == no trigrams

            while (!reader.EndOfStream)
            {
                char third = (char)reader.Read();

                // wishin' this were python about now ;-)
                // ..initialize data structures if needed
                if (!_trigramModel.ContainsKey(first))
                    _trigramModel.Add(first, new SortedList<char, SortedList<char, long>>());
                if (!_trigramModel[first].ContainsKey(second))
                    _trigramModel[first].Add(second, new SortedList<char, long>());

                // ...increment, or initialize count for this trigram
                if (!_trigramModel[first][second].ContainsKey(third))
                    _trigramModel[first][second].Add(third, 1);
                else
                    _trigramModel[first][second][third]++;

                // .. cycle through characters
                first = second;
                second = third;
            }
        }
Example #17
0
File: Form1.cs Project: 3141592/vs
        private void button1_Click(object sender, EventArgs e)
        {
            string sURL;
            sURL = "http://microsoft.com";

            HttpWebRequest myHttpWebRequest;
            myHttpWebRequest = (HttpWebRequest)WebRequest.Create(sURL);
            myHttpWebRequest.UserAgent = "leviticus2195 Test Client";

            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
            Stream streamResponse = myHttpWebResponse.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse);
            Char[] readBuff = new Char[256];
            int count = streamRead.Read(readBuff, 0, 256);
            string content = "";
            while (count > 0)
            {
                String outputData = new String(readBuff, 0, count);
                content = content + outputData;
                count = streamRead.Read(readBuff, 0, 256);
            }
            // Release the response object resources.
            streamRead.Close();
            streamResponse.Close();
            myHttpWebResponse.Close();
            this.richTextBox1.AppendText(content);
        }
Example #18
0
        private void PostJson(string CriminalJson)
        {
            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            byte[] arrB = encode.GetBytes("CriminalJson=" + CriminalJson);

            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://localhost:1246/Upload/Upload");

            myReq.Method = "POST";
            myReq.ContentType = "application/x-www-form-urlencoded";
            myReq.ContentLength = arrB.Length;
            Stream outStream = myReq.GetRequestStream();
            outStream.Write(arrB, 0, arrB.Length);
            outStream.Close();


            //接收HTTP做出的响应
            WebResponse myResp = myReq.GetResponse();
            Stream ReceiveStream = myResp.GetResponseStream();
            StreamReader readStream = new StreamReader(ReceiveStream, encode);
            Char[] read = new Char[256];
            int count = readStream.Read(read, 0, 256);
            string str = null;
            while (count > 0)
            {
                str += new String(read, 0, count);
                count = readStream.Read(read, 0, 256);
            }
            readStream.Close();
            myResp.Close();
            MessageBox.Show(str);
            
        }
Example #19
0
        public string ParseCommentText(StreamReader reader)
        {
            sb.Length = 0;

            int c = reader.Read();
            while (c > -1)
            {
                c = reader.Read();
                if (c == '-')
                {
                    c = reader.Read();
                    if (c == '-')
                    {
                        c = reader.Read();
                        if (c == '>')
                        {
                            break;
                        }
                        sb.Append('-');
                    }
                    sb.Append('-');
                }
                sb.Append((char)c);
            }

            return sb.ToString();
        }
Example #20
0
 public static string ReadPageContentByUrl(string url, string encodingType)
 {
     try
     {
         StringBuilder builder = new StringBuilder();
         HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
         request.AllowAutoRedirect = true;
         HttpWebResponse response = (HttpWebResponse) request.GetResponse();
         if (response.StatusCode == HttpStatusCode.OK)
         {
             Stream responseStream = response.GetResponseStream();
             Encoding encoding = Encoding.GetEncoding(encodingType);
             StreamReader reader = new StreamReader(responseStream, encoding);
             char[] buffer = new char[500];
             for (int i = reader.Read(buffer, 0, 0x100); i > 0; i = reader.Read(buffer, 0, 0x100))
             {
                 string str = new string(buffer, 0, i);
                 builder.Append(str);
             }
             response.Close();
             return builder.ToString();
         }
         response.Close();
         return null;
     }
     catch
     {
         return "网络异常...请稍后再试。";
     }
 }
Example #21
0
        /**
         HTML保存到本地
        **/
        public static void GetToLocalHtml1()
        {
            var url = "http://stock.10jqka.com.cn/fincalendar.shtml#2015-12-18";
            string strBuff = "";//定义文本字符串,用来保存下载的html  
            int byteRead = 0;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            //若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错 误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理   
            Stream reader = webResponse.GetResponseStream();
            ///返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8)  
            StreamReader respStreamReader = new StreamReader(reader, Encoding.UTF8);

            ///分段,分批次获取网页源码  
            char[] cbuffer = new char[1024];
            byteRead = respStreamReader.Read(cbuffer, 0, 256);
            string htm = "";           
            while (byteRead != 0)
            {
                string strResp = new string(cbuffer, 0, byteRead);
                strBuff = strBuff + strResp;
                byteRead = respStreamReader.Read(cbuffer, 0, 256);
            }
            using (StreamWriter sw = new StreamWriter("d:\\GetHtml.html"))//将获取的内容写入文本  
            {
                htm = sw.ToString();//测试StreamWriter流的输出状态,非必须  
                sw.Write(strBuff);
            }
        }
Example #22
0
 public static void AddCurrentRow(int oneChar, StreamReader DataStream)
 {
     if (oneChar == 10 && DataStream.Peek() == 13) { DataStream.Read(); }
     else if (oneChar == 13 && DataStream.Peek() == 10) { DataStream.Read(); }
     CurrentRow += 1;
     CurrentColumn = 0;
 }
Example #23
0
 private void passDeleteComments()
 {
     StreamWriter tempWriter = new StreamWriter("JS_Process.txt", false);
     StreamReader tempReader = new StreamReader("JS_Process_Alt.txt");
     int readByte;
     long BytesWritten = 0;
     bool flagComment = false;
     char chr, prevchr;
     readByte = tempReader.Read();
     prevchr = char.ConvertFromUtf32(readByte).ToCharArray()[0];
     readByte = tempReader.Read();
     while (readByte != -1)
     {
         chr = char.ConvertFromUtf32(readByte).ToCharArray()[0];
         if (prevchr == '/' && chr == '/')
             flagComment = true;
         if (chr == '\n')
             flagComment = false;
         if (!flagComment)
         {
             tempWriter.Write(chr);
             BytesWritten++;
         }
         prevchr = chr;
         readByte = tempReader.Read();
     }
     tempReader.Close();
     tempWriter.Close();
     setOutputValue(BytesWritten);
     setCompressedRatioValue((float)TotalByteCounter / (float)BytesWritten);
 }
Example #24
0
        public TokenEnumeration vid = TokenEnumeration.Unknown; // 0 - unknown, 1 - entity, 2 - literal, 3 - point, 4 - eos

        #endregion Fields

        #region Methods

        public static Token NextToken(StreamReader reader)
        {
            int ne = Next(reader);

            if (ne == -1) return new Token() { vid = TokenEnumeration.Eos };
            if (ne == '.') return new Token() { vid = TokenEnumeration.Point };
            else if (ne == '<')
            {
                StringBuilder sb = new StringBuilder();
                int t;
                while ((t = reader.Read()) != -1 && t != '>')
                {
                    Token.loaded.Append((char)t);
                    sb.Append((char)t);
                }
                if (t == -1) return new Token() { vid = TokenEnumeration.Err };
                string v = sb.ToString();
                if (v.Length >= 400)
                {
                    v = v.Substring(0, 100) + v.Substring(v.Length - 100, 100);
                }
                return new Token() { vid = TokenEnumeration.Entity, Value = v };
            }
            else if (ne == '"')
            {
                StringBuilder sb = new StringBuilder();
                int t;
                while ((t = reader.Read()) != -1 && t != '"')
                {
                    Token.loaded.Append((char)t);
                    if (t == '\\') ReadEscapedChar((char)reader.Read(), sb, reader);
                    else sb.Append((char)t);
                }
                if (t == -1) return new Token() { vid = TokenEnumeration.Err };
                int con = reader.Peek();
                StringBuilder sb2 = new StringBuilder();
                if (con == '@')
                {
                    reader.Read();
                    char c2 = (char)reader.Read();
                    Token.loaded.Append(c2);
                    while (char.IsLetter(c2) || c2 == '-') { sb2.Append(c2); c2 = (char)reader.Read(); Token.loaded.Append(c2); }
                }
                else if (con == '^')
                {
                    reader.Read();
                    reader.Read();
                    char c2 = (char)reader.Read(); Token.loaded.Append(c2);
                    while (c2 != ' ') { sb2.Append(c2); c2 = (char)reader.Read(); Token.loaded.Append(c2); }
                }
                string v = sb.ToString();
                if (v.Length >= 3900) v = v.Substring(0, 3900);
                if (con == '@') return new Token() { vid = TokenEnumeration.Literal, Value = v, lang = sb2.ToString() };
                else if (con == '^') return new Token() { vid = TokenEnumeration.Literal, Value = v, DataType = sb2.ToString() };
                else return new Token() { vid = TokenEnumeration.Literal, Value = v };

            }
            return new Token() { vid = TokenEnumeration.Unknown };
        }
Example #25
0
 public void Parse(StreamReader reader)
 {
     int c = reader.Read();
     while (c > -1)
     {
         c = reader.Read();
     }
 }
		public static List<string> ReadFile(string filename)
		{
			List<string> listFileContent = new List<string>();
			try
			{

				StreamReader reader = new StreamReader(filename, System.Text.Encoding.UTF8, true);

				StringBuilder stringBuilder = new StringBuilder();
				using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
				{
					try
					{                     
						using (StreamReader streamReader = new StreamReader(fileStream))
						{
							char[] fileContents = new char[_bufferSize];
							int charsRead = streamReader.Read(fileContents, 0, _bufferSize);

							// Can't do much with 0 bytes
							if (charsRead == 0)
								throw new Exception("File is 0 bytes");

							while (charsRead > 0)
							{
								stringBuilder.Append(fileContents);
								charsRead = streamReader.Read(fileContents, 0, _bufferSize);
							}

							string[] contentArray = stringBuilder.ToString().Split(new char[] { '\r', '\n' });
							foreach (string line in contentArray)
							{
								if (line.EndsWith("\0"))
								{
									listFileContent.Add(line.Replace("\0", "").Replace("�","\""));

								}
								else
								{
									listFileContent.Add(line);
								}
								//listFileContent.Add(line.Replace("#", ""));
							}
							listFileContent.RemoveAll(s => string.IsNullOrEmpty(s));
						}
					}
					catch (Exception ex)
					{
						Console.WriteLine(ex.StackTrace);
					}
				}

			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.StackTrace);
			}
			return listFileContent;
		}
        private void button1_Click(object sender, EventArgs e)
        {
            /*    OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "PDF |*.pdf | Text|*.txt";
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show(ofd.FileName); //gets path-name
                MessageBox.Show(ofd.SafeFileName); //gets file-name
            } */

            /*    sbyte myByte = -2;
            ushort myShort = 0;
            UInt16 int16 = 0;
            uint myInt = 0;
            UInt32 myInt32 = myInt;
            ulong myLong = 0;
            UInt64 myInt64 = myLong;

            float myFloat = 15135241;
            MessageBox.Show(myFloat.ToString());

            double d = 0.32525;

            char c = 'i';

               */

             /* OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                StreamReader sr = new StreamReader(File.OpenRead(ofd.FileName));
                sr.BaseStream.Position = 0x0A;
                byte[] buffer = new byte[3];
                sr.BaseStream.Read(buffer, 0, 3);
                foreach (byte mybyte in buffer)
                {
                    textBox1.Text += mybyte.ToString("X") + " ";
                    sr.Dispose();
                }
                //textBox1.Text = sr.BaseStream.ReadByte().ToString("X");

                sr.Dispose();
            }

            */
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                StreamReader sr = new StreamReader(File.OpenRead(ofd.FileName));
                //0
                char c = (char)sr.Peek(); //0
                char c1 = (char)sr.Read(); //1
                char c2 = (char)sr.Read();
                MessageBox.Show(c.ToString() + ";" + c1.ToString() + ";" + c2.ToString());
            }
        }
Example #28
0
 public static DateTime DeserializeDate(StreamReader sr, int nextToken)
 {
     if (nextToken != '"') throw new SerializationException("Expecting '\"' at position " + JsonSerialization.PositionInStream(sr) + ". Found " + (char)nextToken);
     nextToken = sr.Read();
     int year = 0;
     for (int i = 0; i < 6 && (nextToken != '-'); i++, nextToken = sr.Read())
         year = year * 10 + (nextToken - '0');
     nextToken = sr.Read();
     int month = nextToken - 48;
     nextToken = sr.Read();
     if (nextToken != '-')
     {
         month = month * 10 + (nextToken - '0');
         if ((nextToken = sr.Read()) != '-') throw new SerializationException("Expecting '-' at position " + JsonSerialization.PositionInStream(sr) + ". Found " + (char)nextToken);
     }
     nextToken = sr.Read();
     int day = nextToken - 48;
     nextToken = sr.Read();
     if (nextToken != '"' && nextToken != ' ' && nextToken != 'T')
     {
         day = day * 10 + (nextToken - '0');
         nextToken = sr.Read();
     }
     for (int i = 0; i < 24 && nextToken != '"'; i++)
         nextToken = sr.Read();
     if (nextToken != '"') throw new SerializationException("Expecting '\"' at position " + JsonSerialization.PositionInStream(sr) + ". Found " + (char)nextToken);
     return new DateTime(year, month, day);
 }
Example #29
0
 public static Guid Deserialize(StreamReader sr, char[] buffer, int nextToken)
 {
     if (nextToken != '"') throw new SerializationException("Expecting '\"' at position " + JsonSerialization.PositionInStream(sr) + ". Found " + (char)nextToken);
     nextToken = sr.Read();
     int i = 0;
     //TODO: optimize
     for (; i < buffer.Length && nextToken != '"'; i++, nextToken = sr.Read())
         buffer[i] = (char)nextToken;
     if (nextToken != '"') throw new SerializationException("Expecting '\"' at position " + JsonSerialization.PositionInStream(sr) + ". Found " + (char)nextToken);
     return new Guid(new string(buffer, 0, i));
 }
Example #30
0
        public override void Execute()
        {
            if (ShowUsage)
            {
                WriteMessage(this.Parser.LogoBanner);
                WriteMessage(this.Parser.Usage);
                return;
            }

            if (String.IsNullOrEmpty(InputFile))
            {
                WriteError("No input text file specified");
                return;
            }

            string outputFile = InputFile + ".lines";

            using (StreamReader reader = new StreamReader(InputFile))
            {
                using (BinaryWriter writer = new BinaryWriter(new FileStream(outputFile, FileMode.Create)))
                {
                    long offset = 0;
                    int c;

                    writer.Write(offset);

                    while (true)
                    {
                        c = reader.Read();
                        if (c == -1)
                            break;
                        offset++;

                        if (c == (int)'\r')
                        {
                            if (reader.Peek() == (int)'\n')
                            {
                                c = reader.Read();
                                if (c == -1)
                                    break;
                                offset++;
                            }

                            writer.Write(offset);
                        }
                        else if (c == (int)'\n')
                        {
                            writer.Write(offset);
                        }
                    }
                }
            }
        }