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
 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 #4
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 #5
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 #6
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);
        }
Example #7
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;
 }
Example #8
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 #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 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 #11
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
        }
Example #12
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);
        }
 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 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 #15
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 #16
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;
        }
Example #17
0
 /// <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 #18
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;
 }
        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 #20
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 #21
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 #22
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);
            }
        }
 /// <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 #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);
                        }
                    }
                }
            }
        }
Example #31
0
        // Create Tree from file.
        private TreeElement CreateTreeFromFile
            (System.IO.StreamReader file, TreeElement treeElement)
        {
            int         value = 0;
            TreeElement left  = null;
            TreeElement right = null;

            if (file.EndOfStream)
            {
                return(treeElement);
            }
            int ch = file.Read(); //  '(' или цифра или ' '

            if (ch == ' ')
            {
                ch = file.Read(); //  '(' или цифра
            }
            if (ch == '(')
            {
                ch = file.Read();  // ' '
                if (ch != ' ')
                {
                    throw new ExceptionTree("Waiting ' '.");
                }

                ch = file.Read();  // sign
                if (ch != '+' && ch != '-' && ch != '*' && ch != '/')
                {
                    throw new ExceptionTree("Waiting sign.");
                }

                value = ch;
                ch    = file.Read(); // ' '
                if (ch != ' ')
                {
                    throw new ExceptionTree("Waiting ' '.");
                }

                left  = CreateTreeFromFile(file, left);
                right = CreateTreeFromFile(file, right);

                if (value == '+')
                {
                    treeElement = new Add(value, left, right);
                }
                if (value == '-')
                {
                    treeElement = new Subtract(value, left, right);
                }
                if (value == '*')
                {
                    treeElement = new Multiply(value, left, right);
                }
                if (value == '/')
                {
                    treeElement = new Divide(value, left, right);
                }
                ch = file.Read(); // ')' или ' '
                if (ch == ' ')
                {
                    ch = file.Read(); // ')'
                }
                if (ch != ')')
                {
                    throw new ExceptionTree("Waiting ).");
                }

                /* ch = file.Read(); // ' '
                 * if (ch != ' ')
                 *   throw new ExceptionTree("Waiting ' '."); */
            }

            else if (ch <= '9' && ch >= '0')
            {
                int number = 0;
                while (ch <= '9' && ch >= '0')
                {
                    number = number * 10 + ch - '0';
                    ch     = file.Read();
                }
                if (ch != ' ')
                {
                    throw new ExceptionTree("Waiting ' '.");
                }

                value       = number;
                treeElement = new Value(value);
            }
            else
            {
                throw new ExceptionTree("Waiting '(' or number.");
            }
            return(treeElement);
        }
Example #32
0
    void Log_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();

        sb.Append("Log" + FD);
        StreamReader sr    = null;
        StreamWriter sw    = null;
        StreamWriter swRaw = null;

        try {
            char[] ca = new char[4096];
            sr = new System.IO.StreamReader(Request.InputStream);
            int cnt = sr.Read(ca, 0, 4096);
            sb.Append("cnt=" + cnt + FD);
            char[] cabs = new char[cnt];
            for (int c = 0; c < cnt; c++)
            {
                cabs[c] = ca[c];
            }
            string str = new String(cabs);

//            Directory.CreateDirectory(Server.MapPath("~/logfiles/"));
            string filespecRaw = Server.MapPath("~/intelligentreminder/logfiles/" +
                                                "RawLog" + "_" + DDCommon.CommonRoutines.dateInCCYYMMDDHHMMSSFormat(DateTime.Now) + ".log");
            swRaw = new StreamWriter(filespecRaw, false);
            swRaw.WriteLine(str);

            sb.Append("str=" + str + FD);
            int index3 = str.IndexOf(FD);

            string sa1 = str.Substring(0, index3);
            string sa2 = str.Substring(index3 + 3);

            string filespec = Server.MapPath("~/intelligentreminder/logfiles/" +
                                             sa1 + "_" + DDCommon.CommonRoutines.dateInCCYYMMDDHHMMSSFormat(DateTime.Now) + ".log");
            sw = new StreamWriter(filespec, true);

            List <DbParameter> parameters = new List <DbParameter>();
            parameters.Add(CommonServerSide.CommonMethods.buildStringParm(
                               "phoneidparm", sa1, ParameterDirection.Input));
            parameters.Add(CommonServerSide.CommonMethods.buildStringParm(
                               "filespecparm", filespec, ParameterDirection.Input));
            //DbParameter returnParm = CommonServerSide.CommonMethods.buildUInt32Parm(
            //    "logidparm", DDCommon.CommonRoutines.NULL_INT, ParameterDirection.Output);
            //parameters.Add(returnParm);
            DataSet ds = CommonServerSide.CommonMethods.getDataSet("uspcreatelogentry", parameters, svm.SessionID);

            int logID = Convert.ToInt32(ds.Tables[0].Rows[0][0]);

            cnt = sa2.Length;
            int cnt2 = cnt;

            if (cnt > 0)
            {
                do
                {
                    sw.Write(sa2);
                    cnt = sr.Read(ca, 0, 4096);
                    if (cnt > 0)
                    {
                        cnt2 += cnt;
                        cabs  = new char[cnt];
                        for (int c = 0; c < cnt; c++)
                        {
                            cabs[c] = ca[c];
                        }
                        sa2 = new string(cabs);
                    }
                } while (cnt > 0);
            }

            Response.Write("ok" + "|" + cnt2);
        } catch (Exception e2) {
            Response.Write("notok" + FD + "Log=" + sb.ToString() + FD + "msg=" + e2.Message);
        } finally {
            try { sr.Close(); } catch { }
            try { sw.Close(); } catch {}
            try { swRaw.Close(); } catch { }
        }
        Response.End();
    }
Example #33
0
    public CSVFile(string path)
    {
        m_Rows = new List <CSVRow>();

        int  curCharVal = 0;
        char curChar;
        bool inQuotes = false;
        var  curField = new StringBuilder();
        var  curRow   = new CSVRow();

        try
        {
            using (var sr = new System.IO.StreamReader(path))
            {
                curCharVal = sr.Read();

                while (curCharVal >= 0)
                {
                    //We can't be sure if the file we've received uses Line Feed (char 10) by itself, or Carriage Return / Line Feed (chars 13 / char 10) to indicate a new line
                    //what we can be sure of, however, is that we really don't care if there's a 13!
                    while (curCharVal == 13)
                    {
                        curCharVal = sr.Read();

                        if (curCharVal == -1)
                        {
                            break;
                        }
                    }

                    //Sanity check, if we ended up with a -1 due to curCharVal == 13 loop...
                    //Should never happen, but god knows what some people's CSV files look like
                    if (curCharVal == -1)
                    {
                        curRow.Fields.Add(curField.ToString());
                        curField.Clear();
                        this.m_Rows.Add(curRow);

                        break;
                    }

                    curChar = (char)curCharVal;

                    if (inQuotes)
                    {
                        //If we're in a quote enclosed field, we need to identify
                        //  if these new quotes are escaped (doubled)
                        //  and if they are, only add a single set of quotes to our
                        //  current field.  If they are not escaped, then we are
                        //  no longer in a quote enclosed field
                        if (curChar == '"')
                        {
                            curCharVal = sr.Read();

                            if (curCharVal >= 0)
                            {
                                curChar = (char)curCharVal;

                                if (curChar != '"')
                                {
                                    inQuotes = false;

                                    //The new character we just imported (presumably a comma)
                                    //  will be handled once we fall through into the next if block below
                                }
                                else
                                {
                                    curField.Append(curChar);
                                }
                            }
                        }
                        else
                        {
                            curField.Append(curChar);
                        }
                    }

                    //This is a separate if statement, rather than an else clause
                    //  because within the if block above, the inQuotes value could be
                    //  set to false, in which case we want to evaluate the logic
                    //  within this code block
                    if (!inQuotes)
                    {
                        if (curField.Length == 0 && curChar == '"')
                        {
                            inQuotes = true;
                        }
                        else if (curChar == ',')
                        {
                            curRow.Fields.Add(curField.ToString());
                            curField.Clear();
                        }
                        else if (curCharVal == 10)
                        {
                            curRow.Fields.Add(curField.ToString());
                            curField.Clear();

                            //We're done with this row, add it to the list and set
                            //  ourselves up for a fresh row.
                            this.m_Rows.Add(curRow);
                            curRow = new CSVRow();
                        }
                        else
                        {
                            curField.Append(curChar);
                        }
                    }


                    curCharVal = sr.Read();

                    //We just reached the end of the file.
                    //  Add the current row to the list of rows before the loop ends
                    if (curCharVal == -1)
                    {
                        curRow.Fields.Add(curField.ToString());
                        curField.Clear();
                    }
                }
            }
        }
        catch
        {
            m_Rows.Clear();
            m_ColumnCount = 0;
        }
    }
Example #34
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtURL.Text))
            {
                txtResponse.Text = "";
                try
                {
                    System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(txtURL.Text);
                    req.Method                   = metodoRequest.Text;
                    req.PreAuthenticate          = true;
                    req.ProtocolVersion          = System.Net.HttpVersion.Version10;
                    req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(txtLogin.Text + ":" + txtSenha.Text));
                    req.Credentials              = new NetworkCredential("username", "password");

                    var type          = req.GetType();
                    var currentMethod = type.GetProperty("CurrentMethod", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(req);

                    var methodType = currentMethod.GetType();
                    methodType.GetField("ContentBodyNotAllowed", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).SetValue(currentMethod, false);

                    System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

                    if (!string.IsNullOrEmpty(txtJson.Text))
                    {
                        byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(txtJson.Text);
                        req.ContentType   = "application/json; charset=utf-8";
                        req.ContentLength = byteArray.Length;
                        var dataStream = req.GetRequestStream();
                        dataStream.Write(byteArray, 0, byteArray.Length);
                        dataStream.Close();
                    }
                    else
                    {
                        //throw new Exception("Erro: JSON não informado.");
                    }

                    System.Net.HttpWebResponse resp          = req.GetResponse() as System.Net.HttpWebResponse;
                    System.IO.Stream           receiveStream = resp.GetResponseStream();
                    System.Text.Encoding       encode        = Encoding.GetEncoding("utf-8");
                    // Pipes the stream to a higher level stream reader with the required encoding format.
                    System.IO.StreamReader readStream = new System.IO.StreamReader(receiveStream, encode);
                    Char[] read = new Char[256];
                    // Reads 256 characters at a time.
                    int count = readStream.Read(read, 0, 256);
                    while (count > 0)
                    {
                        // Dumps the 256 characters on a string and displays the string to the console.
                        String str = new String(read, 0, count);
                        txtResponse.Text += (str);
                        count             = readStream.Read(read, 0, 256);
                    }

                    System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();

                    xDoc.LoadXml(txtResponse.Text);

                    System.Xml.XmlReader xmlReader = new System.Xml.XmlNodeReader(xDoc);

                    DataSet dsXml = new DataSet();

                    dsXml.ReadXml(xmlReader);

                    foreach (DataTable dt in dsXml.Tables)
                    {
                        if (dt.TableName == "value")
                        {
                            gridXMLDataTable.DataSource = dt;
                        }
                    }

                    // Releases the resources of the response.
                    resp.Close();
                    // Releases the resources of the Stream.
                    readStream.Close();
                }
                catch (Exception ex)
                {
                    txtResponse.Text = "Erro ao consumir a API " + txtURL.Text + ". Exceção: " + ex.Message + ". Trace: " + ex.InnerException;
                }
            }
        }
Example #35
0
        public Code postReq(string uri, string post, int i)
        {
            Code result3;

            try
            {
                if (i < this.servers.Length)
                {
                    byte[]                rv     = System.Text.Encoding.UTF8.GetBytes(post);
                    System.Uri            target = new System.Uri(this.servers[i] + uri);
                    System.Net.WebRequest req    = System.Net.WebRequest.Create(target);
                    req.Timeout         = this.timeout;
                    req.Method          = "POST";
                    req.PreAuthenticate = true;
                    req.ContentType     = "application/x-www-form-urlencoded";
                    req.ContentLength   = (long)rv.Length;
                    System.IO.Stream os = req.GetRequestStream();
                    os.Write(rv, 0, rv.Length);
                    os.Close();
                    try
                    {
                        System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)req.GetResponse();
                        string a = "";
                        if (response == null)
                        {
                            i++;
                            result3 = this.postReq(uri, post, i);
                            return(result3);
                        }
                        System.IO.Stream       receiveStream = response.GetResponseStream();
                        System.Text.Encoding   encode        = System.Text.Encoding.GetEncoding("utf-8");
                        System.IO.StreamReader readStream    = new System.IO.StreamReader(receiveStream, encode);
                        char[] read = new char[256];
                        for (int count = readStream.Read(read, 0, 256); count > 0; count = readStream.Read(read, 0, 256))
                        {
                            string str = new string(read, 0, count);
                            a += str;
                        }
                        if (a != "")
                        {
                            ResponseData result = new ResponseData();
                            result.getFromJson(a);
                            Code result2 = new Code(result.getCode().getcode());
                            result3 = result2;
                            return(result3);
                        }
                        response.Close();
                        result3 = new Code();
                        return(result3);
                    }
                    catch (System.Net.WebException e_190)
                    {
                        i++;
                        result3 = this.postReq(uri, post, i);
                        return(result3);
                    }
                }
            }
            catch (System.Net.WebException e_190)
            {
                i++;
                result3 = this.postReq(uri, post, i);
                return(result3);
            }
            result3 = new Code();
            return(result3);
        }
Example #36
0
        public bool getRequestKlk(string uri, string savePath, int i)
        {
            bool result;

            if (i < this.servers.Length)
            {
                System.Uri            target = new System.Uri(this.servers[i] + uri);
                System.Net.WebRequest req    = System.Net.WebRequest.Create(target);
                req.Timeout         = this.timeout;
                req.Method          = "GET";
                req.PreAuthenticate = true;
                req.ContentType     = "application/x-www-form-urlencoded";
                try
                {
                    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)req.GetResponse();
                    if (System.IO.File.Exists(savePath) && response != null && System.DateTime.Compare(System.IO.File.GetLastWriteTime(savePath), response.LastModified) >= 0)
                    {
                        response.Close();
                        result = false;
                        return(result);
                    }
                    if (response != null)
                    {
                        System.IO.Stream       receiveStream = response.GetResponseStream();
                        System.Text.Encoding   encode        = System.Text.Encoding.GetEncoding("utf-8");
                        System.IO.StreamReader readStream    = new System.IO.StreamReader(receiveStream, encode);
                        string a    = "";
                        char[] read = new char[256];
                        for (int count = readStream.Read(read, 0, 256); count > 0; count = readStream.Read(read, 0, 256))
                        {
                            string str = new string(read, 0, count);
                            a += str;
                        }
                        response.Close();
                        readStream.Close();
                        try
                        {
                            System.IO.StreamWriter sw = new System.IO.StreamWriter(savePath, false);
                            sw.Write(a);
                            sw.Close();
                        }
                        catch (System.Exception)
                        {
                            result = false;
                            return(result);
                        }
                    }
                    else
                    {
                        this.getRequestKlk(uri, savePath, i++);
                    }
                }
                catch (System.Net.WebException)
                {
                    i++;
                    result = this.getRequestKlk(uri, savePath, i);
                    return(result);
                }
                result = true;
            }
            else
            {
                result = false;
            }
            return(result);
        }
        private Graph ReadFile(string FileName)
        {
            // Local Variables
            int           ammount = 0;
            string        line;
            StringBuilder temp1 = new StringBuilder();
            StringBuilder temp2 = new StringBuilder();
            char          ch;
            int           num;
            int           course_now = 0;

            try
            {
                // Count the total courses
                System.IO.StreamReader file = new System.IO.StreamReader(FileName);
                while ((line = file.ReadLine()) != null)
                {
                    ammount++;
                }
                file.Close();

                Graph    g           = new Graph(ammount);
                string[] course_code = new string[ammount];

                // Read each course code
                System.IO.StreamReader files = new System.IO.StreamReader(FileName);
                while (!files.EndOfStream)
                {
                    ch = (char)files.Read();
                    if (ch != '.')
                    {
                        if (ch != ',')
                        {
                            temp1.Append(ch);
                        }
                        else
                        {
                            course_code[course_now] = temp1.ToString();
                            course_now++;
                            temp1.Length = 0;
                            while (ch != '.')
                            {
                                ch = (char)files.Read();
                            }
                            ch = (char)files.Read();
                            ch = (char)files.Read();
                        }
                    }
                    else
                    {
                        course_code[course_now] = temp1.ToString();
                        course_now++;
                        temp1.Length = 0;
                        ch           = (char)files.Read();
                        ch           = (char)files.Read();
                    }
                }
                files.Close();
                outputBox.AppendText("Course Code Number : \n");
                for (course_now = 0; course_now < ammount; course_now++)
                {
                    outputBox.AppendText(course_now.ToString());
                    outputBox.AppendText(" = ");
                    outputBox.AppendText(course_code[course_now].ToString());
                    outputBox.AppendText("\n");
                }
                // Read each course code pre-requisite
                course_now = 0;
                int sign = 0;
                System.IO.StreamReader filesn = new System.IO.StreamReader(FileName);
                while (!filesn.EndOfStream)
                {
                    ch = (char)filesn.Read();
                    if (ch != '.')
                    {
                        if (ch != ',')
                        {
                            temp2.Append(ch);
                        }
                        else
                        {
                            if (sign == 0)
                            {
                                sign         = 1;
                                temp2.Length = 0;
                            }
                            else
                            {
                                for (num = 0; num < ammount; num++)
                                {
                                    if (string.Equals(course_code[num], temp2.ToString()))
                                    {
                                        g.addEdges(num, course_now);
                                        num = ammount + 1;
                                    }
                                }
                                temp2.Length = 0;
                            }
                            ch = (char)filesn.Read();
                        }
                    }
                    else
                    {
                        if (sign == 0)
                        {
                            temp2.Length = 0;
                            course_now++;
                        }
                        else
                        {
                            sign = 0;
                            for (num = 0; num < ammount; num++)
                            {
                                if (string.Compare(course_code[num], temp2.ToString()) == 0)
                                {
                                    g.addEdges(num, course_now);
                                    num = ammount + 1;
                                }
                            }
                            temp2.Length = 0;
                            course_now++;
                        }
                    }
                }

                filesn.Close();
                return(g);
            } catch (FileNotFoundException e)
            {
                Console.WriteLine("[Data File Missing] {0}", e);
                outputBox.AppendText("File Not Found !\n");
                return(null);
            }
        }
        private string[] ReadCourses(string FileName)
        {
            // Local Variables
            int           ammount = 0;
            string        line;
            StringBuilder temp1 = new StringBuilder();
            StringBuilder temp2 = new StringBuilder();
            char          ch;
            int           num;
            int           course_now = 0;

            try
            {
                // Count the total courses
                System.IO.StreamReader file = new System.IO.StreamReader(FileName);
                while ((line = file.ReadLine()) != null)
                {
                    ammount++;
                }
                file.Close();

                Graph    g           = new Graph(ammount);
                string[] course_code = new string[ammount];

                // Read each course code
                System.IO.StreamReader files = new System.IO.StreamReader(FileName);
                while (!files.EndOfStream)
                {
                    ch = (char)files.Read();
                    if (ch != '.')
                    {
                        if (ch != ',')
                        {
                            temp1.Append(ch);
                        }
                        else
                        {
                            course_code[course_now] = temp1.ToString();
                            course_now++;
                            temp1.Length = 0;
                            while (ch != '.')
                            {
                                ch = (char)files.Read();
                            }
                            ch = (char)files.Read();
                            ch = (char)files.Read();
                        }
                    }
                    else
                    {
                        course_code[course_now] = temp1.ToString();
                        course_now++;
                        temp1.Length = 0;
                        ch           = (char)files.Read();
                        ch           = (char)files.Read();
                    }
                }
                files.Close();
                return(course_code);
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine("[Data File Missing] {0}", e);
                outputBox.AppendText("File Not Found !\n");
                return(null);
            }
        }
Example #39
0

        
Example #40
0
        /// <summary>
        /// 登录获得post请求后响应的数据
        /// </summary>
        /// <param name="postUrl">请求地址</param>
        /// <param name="referUrl">请求引用地址</param>
        /// <param name="data">请求带的数据</param>
        /// <returns>响应内容</returns>
        public static string PostData(string postUrl, string referUrl, string data)
        {
            string result = "";

            try
            {
                //命名空间System.Net下的HttpWebRequest类
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls ;
                //参照浏览器的请求报文 封装需要的参数 这里参照ie9
                //浏览器可接受的MIME类型
                request.Accept = "*/*";
                //包含一个URL,用户从该URL代表的页面出发访问当前请求的页面
                request.Referer = referUrl;
                //浏览器类型,如果Servlet返回的内容与浏览器类型有关则该值非常有用
                request.UserAgent   = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36";
                request.ContentType = "application/json;charset=UTF-8";
                //请求方式
                request.Method  = "POST";
                request.Timeout = 20000;
                //是否保持常连接
                request.KeepAlive = true;
                request.Headers.Add("Accept-Encoding", "gzip");
                //表示请求消息正文的长度
                request.ContentLength = data.Length;
                Stream postStream = request.GetRequestStream();
                byte[] postData   = Encoding.UTF8.GetBytes(data);
                //将传输的数据,请求正文写入请求流
                postStream.Write(postData, 0, postData.Length);
                postStream.Dispose();
                //写入cookie
                request.CookieContainer = cookiec;
                request.Headers.Add("cookie:" + CookieHeader);
                request.CookieContainer.SetCookies(new Uri(postUrl), CookieHeader);
                //响应
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                response.Cookies = cookiec.GetCookies(request.RequestUri);
                Stream streamReceive;
                string gzip = response.ContentEncoding;
                if (string.IsNullOrEmpty(gzip) || gzip.ToLower() != "gzip")
                {
                    streamReceive = response.GetResponseStream();
                }
                else
                {
                    streamReceive = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                }
                StreamReader sr = new System.IO.StreamReader(streamReceive, Encoding.UTF8);

                if (response.ContentLength > 1)
                {
                    result = sr.ReadToEnd();
                }
                else
                {
                    char[]        buffer = new char[256];
                    int           count  = 0;
                    StringBuilder sb     = new StringBuilder();
                    while ((count = sr.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        sb.Append(new string(buffer));
                    }
                    result = sb.ToString();
                }
                sr.Close();
                response.Close();
                return(result);
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #41
0
        /// <summary>
        /// 登录获得post请求后响应的数据
        /// </summary>
        /// <param name="postUrl">请求地址</param>
        /// <param name="referUrl">请求引用地址</param>
        /// <param name="data">请求带的数据</param>
        /// <returns>响应内容</returns>
        public string PostData(string postUrl, string referUrl, string data)
        {
            string result = "";

            try
            {
                //命名空间System.Net下的HttpWebRequest类
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
                //参照浏览器的请求报文 封装需要的参数 这里参照ie9
                //浏览器可接受的MIME类型
                request.Accept = "text/plain, */*; q=0.01";
                //包含一个URL,用户从该URL代表的页面出发访问当前请求的页面
                request.Referer = referUrl;
                //浏览器类型,如果Servlet返回的内容与浏览器类型有关则该值非常有用
                request.UserAgent   = "ShengDiYaGe/1.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)";
                request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                //请求方式
                request.Method  = "POST";
                request.Timeout = 20000;
                //是否保持常连接
                request.KeepAlive = true;
                request.Headers.Add("Accept-Encoding", "gzip, deflate");
                //表示请求消息正文的长度
                request.ContentLength = data.Length;
                Stream postStream = request.GetRequestStream();
                byte[] postData   = Encoding.UTF8.GetBytes(data);
                //将传输的数据,请求正文写入请求流
                postStream.Write(postData, 0, postData.Length);
                postStream.Dispose();
                //写入cookie
                request.CookieContainer = cookiec;
                request.Headers.Add("cookie:" + this.CookieHeader);
                request.CookieContainer.SetCookies(new Uri(postUrl), this.CookieHeader);
                //响应
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                response.Cookies = cookiec.GetCookies(request.RequestUri);
                Stream streamReceive;
                string gzip = response.ContentEncoding;
                if (string.IsNullOrEmpty(gzip) || gzip.ToLower() != "gzip")
                {
                    streamReceive = response.GetResponseStream();
                }
                else
                {
                    streamReceive = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                }
                StreamReader sr = new System.IO.StreamReader(streamReceive, Encoding.UTF8);

                if (response.ContentLength > 1)
                {
                    result = sr.ReadToEnd();
                }
                else
                {
                    char[]        buffer = new char[256];
                    int           count  = 0;
                    StringBuilder sb     = new StringBuilder();
                    while ((count = sr.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        sb.Append(new string(buffer));
                    }
                    result = sb.ToString();
                }
                sr.Close();
                response.Close();
                return(result);
            }
            catch (Exception)
            {
            }
            finally
            {
                Console.WriteLine("!!!!!!!!!");
            }
            return(result);
        }
Example #42
0
        /// <summary>
        /// 已登录持有cookie进行post
        /// </summary>
        /// <param name="postUrl"></param>
        /// <param name="referUrl"></param>
        /// <param name="data"></param>
        /// <param name="cookiec"></param>
        /// <returns></returns>
        public string PostData(string postUrl, string referUrl, string data, CookieContainer cookiec)
        {
            //data = System.Web.HttpUtility.UrlEncode(data);
            string result = "";

            try
            {
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(postUrl);
                myHttpWebRequest.AllowAutoRedirect = true;
                myHttpWebRequest.KeepAlive         = true;
                myHttpWebRequest.Accept            = "*/*";
                myHttpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
                myHttpWebRequest.CookieContainer = cookiec;
                myHttpWebRequest.UserAgent       = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 2.0.50727)";
                myHttpWebRequest.ContentType     = "application/x-www-form-urlencoded; charset=UTF-8";
                myHttpWebRequest.Referer         = referUrl;
                myHttpWebRequest.Method          = "POST";
                myHttpWebRequest.Timeout         = 80000;
                myHttpWebRequest.ContentLength   = data.Length;
                Stream postStream = myHttpWebRequest.GetRequestStream();
                byte[] postData   = Encoding.UTF8.GetBytes(data);
                postStream.Write(postData, 0, postData.Length);
                postStream.Dispose();
                HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse();
                response.Cookies = cookiec.GetCookies(myHttpWebRequest.RequestUri);
                Stream streamReceive;
                string gzip = response.ContentEncoding;
                if (string.IsNullOrEmpty(gzip) || gzip.ToLower() != "gzip")
                {
                    streamReceive = response.GetResponseStream();
                }
                else
                {
                    streamReceive = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                }
                StreamReader sr = new System.IO.StreamReader(streamReceive, Encoding.UTF8);
                if (response.ContentLength > 1)
                {
                    result = sr.ReadToEnd();
                }
                else
                {
                    char[]        buffer = new char[256];
                    int           count  = 0;
                    StringBuilder sb     = new StringBuilder();
                    while ((count = sr.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        sb.Append(new string(buffer));
                    }
                    result = sb.ToString();
                }
                sr.Close();
                response.Close();
                string s = result;
                return(s);
            }
            catch { }
            finally
            {
                Console.WriteLine("!!!!!!!!!");
            }
            return("");
        }
Example #43
0
        /// <summary>
        /// 发布评论
        /// </summary>
        /// <param name="PostNo">纯数字ac号</param>
        /// <param name="data"></param>
        public static string comment(string PostNo, string data, CookieContainer cookiec)
        {
            //posturl
            //http://www.acfun.cn/comment.aspx
            //data:
            //name:sendComm()
            //token:mimiko
            //quoteId:0
            //text:%E8%A6%81%E9%82%A3%E4%B9%88%E5%A4%9A%E7%9F%B3%E6%B2%B9%E5%B9%B2%E5%98%9B%EF%BC%8C%E5%8D%96%E4%BA%86%E5%8D%96%E4%BA%86
            //cooldown:5000
            //contentId:1832378
            //name=sendComm()&token=mimiko&quoteId=0&text=%E8%A6%81%E9%82%A3%E4%B9%88%E5%A4%9A%E7%9F%B3%E6%B2%B9%E5%B9%B2%E5%98%9B%EF%BC%8C%E5%8D%96%E4%BA%86%E5%8D%96%E4%BA%86&cooldown=5000&contentId=1832378
            //refer
            //http://www.acfun.cn/a/ac1832378
            data = System.Web.HttpUtility.UrlEncode(data);
            data = "name=sendComm()&token=mimiko&quoteId=0&text=" + data + "&cooldown=5000&contentId=" + PostNo + "&quoteName=";
            string result = "";

            try
            {
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.acfun.cn/comment.aspx");
                myHttpWebRequest.AllowAutoRedirect = true;
                myHttpWebRequest.KeepAlive         = true;
                myHttpWebRequest.Accept            = "*/*";
                myHttpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
                myHttpWebRequest.CookieContainer = cookiec;
                myHttpWebRequest.UserAgent       = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 2.0.50727)";
                myHttpWebRequest.ContentType     = "application/x-www-form-urlencoded; charset=UTF-8";
                myHttpWebRequest.Referer         = "http://www.acfun.cn/a/ac" + PostNo;
                myHttpWebRequest.Method          = "POST";
                myHttpWebRequest.Timeout         = 10000;
                myHttpWebRequest.ContentLength   = data.Length;
                Stream postStream = myHttpWebRequest.GetRequestStream();
                byte[] postData   = Encoding.UTF8.GetBytes(data);
                postStream.Write(postData, 0, postData.Length);
                postStream.Dispose();
                HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse();
                response.Cookies = cookiec.GetCookies(myHttpWebRequest.RequestUri);
                Stream streamReceive;
                string gzip = response.ContentEncoding;
                if (string.IsNullOrEmpty(gzip) || gzip.ToLower() != "gzip")
                {
                    streamReceive = response.GetResponseStream();
                }
                else
                {
                    streamReceive = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                }
                StreamReader sr = new System.IO.StreamReader(streamReceive, Encoding.UTF8);
                if (response.ContentLength > 1)
                {
                    result = sr.ReadToEnd();
                }
                else
                {
                    char[]        buffer = new char[256];
                    int           count  = 0;
                    StringBuilder sb     = new StringBuilder();
                    while ((count = sr.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        sb.Append(new string(buffer));
                    }
                    result = sb.ToString();
                }
                sr.Close();
                response.Close();
                string s = result;
                return(s);
            }
            catch (Exception)
            {
                //throw;
            }
            return("");
        }
Example #44
0
 /// <summary>
 /// 以Post 形式提交数据到 uri
 /// </summary>
 /// <param name="uri"></param>
 /// <param name="files"></param>
 /// <param name="values"></param>
 /// <returns></returns>
 private static byte[] Post(Uri uri, UploadFile file, Dictionary <string, string> values, Dictionary <string, string> valuesend)
 {
     try
     {
         string         boundary = "-----------------------------abxdjqvibshi";
         HttpWebRequest request  = (HttpWebRequest)WebRequest.Create(uri);
         request.Accept = "*/*";
         request.Headers.Add("Accept-Encoding", "gzip, deflate");
         request.Headers.Add("Accept-Language", "en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2,ja;q=0.2,fr;q=0.2,ru;q=0.2");
         HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
         request.CachePolicy = noCachePolicy;
         request.KeepAlive   = true;
         request.ContentType = "multipart/form-data; boundary=" + boundary;
         request.Method      = "POST";
         request.Referer     = "http://cdn.aixifan.com/player/libs/ACUserProfileUploader.swf";
         request.UserAgent   = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36";
         request.Timeout     = 100000;
         request.KeepAlive   = true;
         request.Host        = "www.acfun.cn";
         request.Headers.Add("Origin", "http://cdn.aixifan.com");
         request.Headers.Add("x-requested-with", "ShockwaveFlash/21.0.0.216");
         request.CookieContainer = cookiec;
         MemoryStream stream = new MemoryStream();
         byte[]       line   = Encoding.ASCII.GetBytes("\r\n" + boundary + "\r\n");
         //提交文本字段
         if (values != null)
         {
             string format = "\r\n" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
             foreach (string key in values.Keys)
             {
                 stream.Write(line, 0, line.Length);
                 string s    = string.Format(format, key, values[key]);
                 byte[] data = Encoding.UTF8.GetBytes(s);
                 stream.Write(data, 0, data.Length);
             }
         }
         //提交文件
         if (file != null)
         {
             stream.Write(line, 0, line.Length);
             string fformat = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
             string s       = string.Format(fformat, file.Name, file.Filename);
             byte[] data    = Encoding.UTF8.GetBytes(s);
             stream.Write(data, 0, data.Length);
             stream.Write(file.Data, 0, file.Data.Length);
         }
         if (valuesend != null)
         {
             string format = "\r\n" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
             foreach (string key in valuesend.Keys)
             {
                 string s    = string.Format(format, key, valuesend[key]);
                 byte[] data = Encoding.UTF8.GetBytes(s);
                 stream.Write(data, 0, data.Length);
             }
             string endline = "\r\n" + boundary + "--";
             byte[] enddata = Encoding.UTF8.GetBytes(endline);
             stream.Write(enddata, 0, enddata.Length);
         }
         request.ContentLength = stream.Length;
         Stream requestStream = request.GetRequestStream();
         stream.Position = 0L;
         stream.CopyTo(requestStream);
         stream.Close();
         requestStream.Close();
         using (var response = request.GetResponse())
             using (var responseStream = response.GetResponseStream())
                 using (var mstream = new MemoryStream())
                 {
                     string result = "";
                     responseStream.CopyTo(mstream);
                     //return mstream.ToArray();
                     StreamReader sr = new System.IO.StreamReader(mstream, Encoding.UTF8);
                     if (response.ContentLength > 1)
                     {
                         result = sr.ReadToEnd();
                     }
                     else
                     {
                         char[]        buffer = new char[256];
                         int           count  = 0;
                         StringBuilder sb     = new StringBuilder();
                         while ((count = sr.Read(buffer, 0, buffer.Length)) > 0)
                         {
                             sb.Append(new string(buffer));
                         }
                         result = sb.ToString();
                     }
                     sr.Close();
                     response.Close();
                     string s = result;
                     return(null);
                 }
     }
     catch (Exception e) { var error = e; }
     finally { }
     return(null);
 }