Peek() private method

private Peek ( ) : int
return int
Example #1
0
        private IEnumerable<Record> ReadRecords(string fileName)
        {
            var stringBuilder = new StringBuilder();

            using (var reader = new StreamReader(fileName))
            {
                ReadOnlyCollection<string> header;
                if (reader.Peek() >= 0)
                {
                    var first = this.ParseLine(reader.ReadLine(), stringBuilder).ToArray();

                    header = new ReadOnlyCollection<string>(first);
                }
                else
                {
                    yield break;
                }

                for (var i = 0; i < this._numberRecordsToSkip && reader.Peek() >= 0; i++)
                {
                    reader.ReadLine();
                }

                while (reader.Peek() >= 0)
                {
                    var items = this.ParseLine(reader.ReadLine(), stringBuilder).ToArray();

                    yield return new Record(header, items);
                }
            }
        }
 public virtual List<student> ReadAll(string fileName)
 {
     FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
     StreamReader sr = new StreamReader(file);
     List<student> result = new List<student>();
     if (Indexed)
     {
         FileStream fs = new FileStream("Index.txt", FileMode.Open, FileAccess.Read);
         StreamReader Sr = new StreamReader(fs);
         if (Sr.Peek() != -1)
             CurrentIndexVal1 = int.Parse(Sr.ReadLine());
         while (Sr.Peek() != -1)
         {
             CurrentIndexVal2 = int.Parse(Sr.ReadLine());
             student std = this.Read(sr);
             result.Add(std);
             CurrentIndexVal1 = CurrentIndexVal2;
         }
     }
     else
     {
         while (sr.Peek() != -1)
         {
             student std = this.Read(sr);
             result.Add(std);
         }
     }
     sr.Close();
     return result;
 }
Example #3
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 #4
0
        /// <summary>
        /// 将Csv读入DataTable
        /// </summary>
        /// <param name="filePath">csv文件路径</param>
        /// <param name="n">表示第n行是字段title,第n+1行是记录开始</param>
        public static DataTable CsvToDt(string filePath, int n)
        {
            DataTable dt = new DataTable();
            StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8, false);
            int i = 0;
            int m = 0;
            reader.Peek();
            while (reader.Peek() > 0)
            {
                m = m + 1;
                string str = reader.ReadLine();
                if (m >= n + 1)
                {
                    string[] split = str.Split(',');

                    System.Data.DataRow dr = dt.NewRow();
                    for (i = 0; i < split.Length; i++)
                    {
                        dr[i] = split[i];
                    }
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }
Example #5
0
        /// <summary>
        ///     将CSV格式的流读入table
        /// </summary>
        /// <param name="ms">数据流</param>
        /// <param name="n">整型值</param>
        /// <returns>DataTable</returns>
        public static DataTable Csv2DataTable(MemoryStream ms, int n)
        {
            var dt = new DataTable();
            using (var reader = new StreamReader(ms))
            {
                int i = 0, m = 0;
                reader.Peek();
                while (reader.Peek() > 0)
                {
                    m = m + 1;
                    string str = reader.ReadLine();
                    if (m >= n + 1)
                    {
                        string[] split = str.Split(',');

                        DataRow dr = dt.NewRow();
                        for (i = 0; i < split.Length; i++)
                        {
                            dr[i] = split[i];
                        }
                        dt.Rows.Add(dr);
                    }
                }
                return dt;
            }
        }
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
        public void Split()
        {
            int split_num = 1;
            string destFilePart = Path.Combine(_opts.WorkingDirectory, string.Format(_opts.SplitFilePattern, split_num));
            StreamWriter sw = new StreamWriter(destFilePart);
            long read_line = 0;
            using (StreamReader sr = new StreamReader(_opts.InputFileName))
            {
                while (sr.Peek() >= 0)
                {

                    // Progress reporting
                    //if (++read_line % rowDivider == 0)
                    //    Console.Write("{0:f2}%   \r",
                    //      100.0 * sr.BaseStream.Position / sr.BaseStream.Length);

                    // Copy a line
                    sw.WriteLine(sr.ReadLine());

                    // If the file is big, then make a new split,
                    // however if this was the last line then don't bother
                    if (read_line / split_num > _opts.FileSizeDivider && sr.Peek() >= 0)
                    {
                        sw.Close();
                        destFilePart = Path.Combine(_opts.WorkingDirectory, string.Format(_opts.SplitFilePattern, split_num++));
                        sw = new StreamWriter(destFilePart);
                    }
                }
            }
            sw.Close();
        }
Example #8
0
        private string ReadNumber(StreamReader FileReader)
        {
            string TempString = "";
            while ((FileReader.Peek() >= 0) && ((Char.IsNumber((char)FileReader.Peek()))
                || ((char)FileReader.Peek() == '.')))
            {

                TempString += (char)FileReader.Read();
            }
            if ((((char)FileReader.Peek()) == 'E') || (((char)FileReader.Peek()) == 'e'))
            {
                TempString += (char)FileReader.Read();
                while (Char.IsNumber((char)FileReader.Peek()))
                {
                    TempString += (char)FileReader.Read();
                }
                if ((((char)FileReader.Peek()) == '+') || (((char)FileReader.Peek()) == '-'))
                {
                    TempString += (char)FileReader.Read();
                    while (Char.IsNumber((char)FileReader.Peek()))
                    {
                        TempString += (char)FileReader.Read();
                    }

                }

            }
            return TempString;
        }
        public static List<Employee> LoadEntries()
        {
            List<Employee> list = null;

            try {
                using (FileStream fileStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read)) {
                    using (StreamReader reader = new StreamReader(fileStream)) {

                        //Populate List from lines in file
                        list = new List<Employee>();
                        while (reader.Peek() != -1) {
                            Employee employee = new Employee();

                            for (int i = 0; i <= 3; i++) {
                                string line;

                                if (reader.Peek() != -1) {
                                    line = reader.ReadLine();
                                } else {
                                    break;
                                }

                                switch (i) {
                                    case 0:
                                        employee.firstName = line;
                                        break;

                                    case 1:
                                        employee.lastName = line;
                                        break;

                                    case 2:
                                        employee.employeeID = Convert.ToInt32(line.Substring(2));
                                        break;

                                    case 3:
                                        employee.department = line;
                                        break;
                                }
                            }

                            list.Add(employee);

                            if (reader.Peek() != -1) {
                                reader.ReadLine();
                            }
                        }
                    }
                }
            } catch (FileNotFoundException) {
                MessageBox.Show("File not found: " + inputFile, "File Error");
            } catch (DirectoryNotFoundException) {
                MessageBox.Show("Directory not found: " + inputDir, "Directory Error");
            } catch (IOException ex) {
                MessageBox.Show(ex.GetType() + ": " + ex.Message, "IOException");
            }

            return list;
        }
Example #10
0
 /// <summary>
 /// 从CSV文件总获取联系人的方法
 /// </summary>
 /// <param name="fileStream">CSV文件流</param>
 /// <returns>联系人字典</returns>
 public static Dictionary<string, string> GetContactAccessor(Stream fileStream)
 {
     System.IO.StreamReader reader = new System.IO.StreamReader(fileStream, Encoding.Default);
     Dictionary<string, string> contacts = new Dictionary<string, string>(); //存放读取出来的csv联系人
     //根据表头确定联系人的名字在什么地方。
     int lastNameIndex = -1;
     int firstNameIndex = -1;
     if (reader.Peek() > 0)
     {
         string contact = reader.ReadLine();
         contact = contact.Replace("\"", "");
         string[] contactArray = contact.Split(new char[] { ',' });
         for (int i = 0; i < contactArray.Length; i++)
         {
             if (string.IsNullOrEmpty(contactArray[i]))
                 continue;
             switch (contactArray[i].ToLower())
             {
                 case "姓名":
                     lastNameIndex = i;
                     break;
                 case "name":
                     lastNameIndex = i;
                     break;
                 case "名":
                     lastNameIndex = i;
                     break;
                 case "姓":
                     firstNameIndex = i;
                     break;
                 default:
                     break;
             }
         }
     }
     //循环获取联系人名和Email信息
     while (reader.Peek() > 0)
     {
         string contact = reader.ReadLine();
         contact = contact.Replace("\"", "");
         string[] contactArray = contact.Split(new char[] { ',' });
         string name = string.Empty;
         if (firstNameIndex != -1)
             name += contactArray[firstNameIndex];
         if (lastNameIndex != -1)
             name += contactArray[lastNameIndex];
         Regex regex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
         Match match = regex.Match(contact);
         string email = null;
         if (match.Success)
             email = match.Value;
         if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(name))
             contacts[email] = name;
     }
     return contacts;
 }
Example #11
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter filepath to read from");
            var inputFile = Console.ReadLine();
            var inputFileName = string.IsNullOrWhiteSpace(inputFile) ? @"C:\users\vshardul\desktop\testRunEntries.txt" : inputFile;

            Console.WriteLine("Enter output filepath");
            var outputFile = Console.ReadLine();
            var outputFileName = string.IsNullOrWhiteSpace(outputFile) ? @"Output.txt" : outputFile;

            Console.WriteLine("Entries to ignore - ");
            var entriesToIgnore = long.Parse(Console.ReadLine());

            if (!File.Exists(inputFileName))
            {
                Console.WriteLine("Invalid input file path");
                return;
            }

            using (var inputStream = new StreamReader(inputFileName))
            {
                if (inputStream.Peek() < 0)
                {
                    Console.WriteLine("Enpty Stream");
                    return;
                }

                var headerRow = inputStream.ReadLine();

                int ignoreCount = 0;
                while (ignoreCount < entriesToIgnore && inputStream.Peek() >= 0)
                {
                    inputStream.ReadLine();
                    ignoreCount++;
                }

                using (var outputStream = new StreamWriter(outputFileName))
                {
                    outputStream.WriteLine(headerRow);
                    while (inputStream.Peek() >= 0)
                    {
                        var line = inputStream.ReadLine();
                        if (line != null && line.Split('\t').Length == headerRow.Split('\t').Length)
                        {
                            outputStream.WriteLine(line);
                        }
                    }

                    outputStream.Close();
                }

                inputStream.Close();
            }

            Console.WriteLine("File content trnafer successfull");
        }
Example #12
0
 public int GetStreamDigits(StreamReader sr, int count=2)
 {
     char inp; string nums="";
     if(count<1||sr==null||sr.Peek()<0) return -1;
     while(nums.Length<count && sr.Peek()>=0) {
         do { inp=(char)sr.Read(); } while(!Char.IsDigit(inp) && sr.Peek()>=0);
         if(Char.IsDigit(inp)) nums+=inp;
     }
     return nums.Length>0?int.Parse(nums):-1;
 }
Example #13
0
 public String ReadAndDecode(StreamReader sr)
 {
     String ts=sr.ReadLine();
     while((sr.Peek()==9)||(sr.Peek()==32))
     {
         sr.Read();
         ts=ts+'\r'+'\n'+sr.ReadLine();
     }
     return Decode(ts);
 }
Example #14
0
		public void Formatting()
		{
			var o = DFormattingOptions.CreateDStandard();
			
			bool isTargetCode = false;
			
			var rawCode = string.Empty;
			var sb = new StringBuilder();
			var l = new List<Tuple<string,string>>();
			
			using(var st = Assembly.GetExecutingAssembly().GetManifestResourceStream("formatterTests")){
				using(var r = new StreamReader(st))
				{
					int n;
					while((n=r.Read()) != -1)
					{
						if((n == ':' && r.Peek() == ':') || (n == '#' && r.Peek() == '#'))
						{
							r.ReadLine();
							
							if(n == '#')
							{								
								if(isTargetCode)
								{
									l.Add(new Tuple<string,string>(rawCode, sb.ToString().Trim()));
									sb.Clear();
								}
								else
								{
									rawCode = sb.ToString().Trim();
									sb.Clear();
								}
								
								isTargetCode = !isTargetCode;
							}
						}
						else if(n == '\r' || n == '\n')
						{
							sb.Append((char)n);
						}
						else
						{
							sb.Append((char)n);
							sb.AppendLine(r.ReadLine());
						}
					}
				}
			}
			
			foreach(var tup in l)
			{
				Fmt(tup.Item1, tup.Item2, o);
			}
		}
        public static int CountProteins(FileStream proteinFastaDatabase, bool onTheFlyDecoys, out int targetProteins, out int decoyProteins, out int onTheFlyDecoyProteins)
        {
            targetProteins = 0;
            decoyProteins = 0;
            onTheFlyDecoyProteins = 0;

            StreamReader fasta = new StreamReader(proteinFastaDatabase);

            string description = null;

            while(true)
            {
                string line = fasta.ReadLine();

                if(line.StartsWith(">"))
                {
                    description = line.Substring(1);
                }

                if(fasta.Peek() == '>' || fasta.Peek() == -1)
                {
                    if(description.Contains(Protein.DECOY_IDENTIFIER))
                    {
                        if(onTheFlyDecoys)
                        {
                            throw new ArgumentException(proteinFastaDatabase.Name + " contains decoy proteins; database should not contain decoy proteins when \"create target–decoy database on the fly\" option is enabled");
                        }
                        decoyProteins++;
                    }
                    else
                    {
                        targetProteins++;
                        if(onTheFlyDecoys)
                        {
                            onTheFlyDecoyProteins++;
                        }
                    }

                    description = null;

                    if(fasta.Peek() == -1)
                    {
                        break;
                    }
                }
            }

            proteinFastaDatabase.Seek(0, SeekOrigin.Begin);

            return targetProteins + decoyProteins + onTheFlyDecoyProteins;
        }
Example #16
0
        void ConsumeEmptyLines(StreamReader stream)
        {
            while(
               (stream.Peek() == '\n' ||
                stream.Peek() == '\r' ||
                stream.Peek() == '\f') &&
                stream.Peek() > -1)
            {
                if(stream.EndOfStream)
                    break;
                stream.ReadLine();

                // Console.WriteLine("QACategory removing nonessential line: " + stream.ReadLine());
            }
        }
Example #17
0
		    public bool Check(string code) {
			    using (var reader = new StreamReader(env.ROOT + "lib" + env.DELIM + "colors.csv")) {
				    while (reader.Peek() != -1) {
					    string[] line = reader.ReadLine().Split(',');
					    if (code.Split(new string[] { ",", "-" }, StringSplitOptions.None).Length == 3) {
						    string[] temp = code.Split(new string[] { ",", "-" }, StringSplitOptions.None);
						    if (line[1] == String.Format("{0}-{1}-{2}", temp[0], temp[1], temp[2])) 
                                return true;
					    } else if (code[1] == '#') {
						    string temp = code.Substring(1, code.Length - 1);
						    if (line[2].Substring(1, line[2].Length - 1) == temp) 
                                return true;
					    } else {
						    string letters = String.Empty;
						    for (int i = 0; i < code.Length; ++i) {
							    char c = char.ToLower(code[i]);
							    if ((int)c < 122 && (int)c > 97) 
                                    letters += c.ToString();
						    }
                            if (letters.Length == code.Length && letters == code)
                                return true;
					    }
				    }
				    reader.Dispose();
			    }
			    return false;
		    }
Example #18
0
 private void ParseTests(StreamReader standardOutput, ITestCaseDiscoverySink discoverySink, IMessageLogger logger, string source)
 {
     string testcase = "";
     bool testsStarted = false;
     Regex testCaseMatch = new Regex(@".*\.$");
     while (standardOutput.Peek() != -1)
     {
         string line = standardOutput.ReadLine();
         if (!string.IsNullOrEmpty(line))
         {
             if (testCaseMatch.IsMatch(line))
             {
                 testsStarted = true;
                 testcase = line.Trim();
                 logger.SendMessage(TestMessageLevel.Informational, string.Format("Found test case {0}", testcase.Trim('.')));
             }
             else if(testsStarted)
             {
                 TestCase test = new TestCase(testcase + line.Trim(), Plugin.VisualStudio2012.GTest.GTestExecutor.ExecutorUri, source);
                 discoverySink.SendTestCase(test);
                 logger.SendMessage(TestMessageLevel.Informational, string.Format("Found test {0}", testcase + line.Trim()));
             }
         }
     }
 }
Example #19
0
        //获取远程服务器ATN结果,验证是否是支付宝服务器发来的请求
        public static string GetHttp(string aStrUrl, int timeout)
        {
            string strResult;
            try
            {
                var myReq = (HttpWebRequest)WebRequest.Create(aStrUrl);
                myReq.Timeout = timeout;
                var httpWResp = (HttpWebResponse)myReq.GetResponse();
                Stream myStream = httpWResp.GetResponseStream();
                var sr = new StreamReader(myStream, Encoding.Default);
                var strBuilder = new StringBuilder();
                while (-1 != sr.Peek())
                {
                    strBuilder.Append(sr.ReadLine());
                }

                strResult = strBuilder.ToString();
            }
            catch (Exception exp)
            {

                strResult = "错误:" + exp.Message;
            }

            return strResult;
        }
        // <summary>
        /// The extract trades.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        /// <exception cref="InvalidDataException">
        /// </exception>
        public override async Task<List<Trade>> ExtractTrades(Stream source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            List<Trade> returnList = new List<Trade>();

            using (var sr = new StreamReader(source))
            {
                while (sr.Peek() > -1)
                {
                    var line = sr.ReadLine().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    try
                    {
                        var trade = this.ExtractTrade(line);
                        returnList.Add(trade);
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidDataException("Provided data is of invalid format", ex);
                    }                  
                }  
            }

            return returnList;
        }
Example #21
0
 public static void Load()
 {
     string file = System.IO.Directory.GetCurrentDirectory() + "\\DataArrays\\Lore.txt";
     FileStream strLib = File.Open(file, FileMode.Open);
     using (StreamReader read = new StreamReader(strLib, Encoding.UTF7))
     {
         while (read.Peek() >= 0)
         {
             Lore toAdd = new Lore(read.ReadLine());
             if (!Categories.Contains(toAdd.Category))
             {
                 Categories.Add(toAdd.Category);
             }
             if(!CategoryLists.ContainsKey(toAdd.Category))
             {
                 CategoryLists.Add(toAdd.Category, new List<Lore>());
             }
             CategoryLists[toAdd.Category].Add(toAdd);
             _library.Add(toAdd.Id, toAdd);
             _sortedLores.Add(toAdd);
         }
     }
     Categories.Sort();
     _sortedLores.Sort();
 }
Example #22
0
        public static List<Calendar> LoadCalendarList(string path, DateTime week)
        {
            List<string> list = new List<string>(); //lijst van alle regels
            List<Calendar> calendarlist = new List<Calendar>();

            using (StreamReader sr = new StreamReader(path))
            {
                while (sr.Peek() >= 0)
                {
                    list.Add(sr.ReadLine()); //txt opsplitsen per lijn
                }
                Console.WriteLine("Calender loaded");
            }

            int count = 13; //aantal velden in regel
            for (int i = 0; i < list.Count; i++)
            {
                string[] item = new string[count];
                item = list[i].Split(new char[] { '\t' }); //regel opsplitsen per tab

                Calendar c = new Calendar();
                c.Teachers = c.MakeArray(item[3]); //3 = docent
                c.Abbreviation = item[4]; //4 = afkorting
                c.Subject = item[5]; //5 = onderwerp
                c.Classes = c.MakeArray(item[6]); //6 = klas
                c.Classrooms = c.MakeArray(item[7]); //7 = lokaal
                c.Departments = c.MakeDepartments(c.Classes);
                c.Start = c.MakeStart(week, item[12], item[13]); //12 = dag, 13 = startuur
                c.End = c.MakeEnd(c.Start, item[1]); //1 = duur

                calendarlist.Add(c);
            }

            return calendarlist;
        }
Example #23
0
        public static void Load()
        {
            
            if (Directory.Exists(baseAccountPath) == false)
                Directory.CreateDirectory(baseAccountPath);
            
            Account = AccountSettings.Load(baseAccountPath + "\\Accounts.xusr");

            IExtendFramework.Text.INIDocument doc = null;
            if (!File.Exists(baseAccountPath + "\\..\\Settings.ini"))
            {
                doc = new IExtendFramework.Text.INIDocument();
                doc["general"]["WaitToCheckForEmailSeconds"] = 30000.ToString();
                doc.Save(baseAccountPath + "\\..\\Settings.ini");
            }
            doc = new IExtendFramework.Text.INIDocument(baseAccountPath + "\\..\\Settings.ini");
            WaitToCheckForEmailSeconds = doc.GetInt32("general", "WaitToCheckForEmailSeconds");

            string base2 = baseAccountPath + "\\..\\Emails.list"; // up one folder
            if (!File.Exists(base2))
            {
                using (StreamWriter sw = new StreamWriter(base2))
                {
                    sw.WriteLine(Account.Accounts[0].EmailAddress);
                    sw.Close();
                }
            }
            StreamReader sr = new StreamReader(base2);
            while (sr.Peek() != -1)
                Emails.Add(sr.ReadLine());
            sr.Close();
        }
Example #24
0
 public string ParseFileReadValue(string key)
 {
     using (StreamReader reader =
         new StreamReader(_iniFileName))
     {
         do
         {
             string line = reader.ReadLine();
             Match match =
                 _iniKeyValuePatternRegex.Match(line);
             if (match.Success)
             {
                 string currentKey =
                     match.Groups["Key"].Value as string;
                 if (currentKey != null &&
                     currentKey.Trim().CompareTo(key) == 0)
                 {
                     string value =
                         match.Groups["Value"].Value as string;
                     return value;
                 }
             }
         } while (reader.Peek() != -1);
     }
     return null;
 }
Example #25
0
 private void GetNameList()
 {
     string strFile = m_rootPath + "Record.txt";
     try
     {
         if (File.Exists(strFile))
         {
             using (StreamReader sr = new StreamReader(strFile,Encoding.GetEncoding("gb2312")))
             {
                 ArrayList str_list = new ArrayList();
                 while (sr.Peek() >= 0)
                 {
                     string str = sr.ReadLine();
                     str_list.Add(str);                            
                 }
                 int count=str_list.Count;
                 m_nameList = str_list.GetRange(3, count - 3);
             }
         }
     }
     catch (System.Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Example #26
0
        //------------------------------------------------------------------------------
        // buildLoadInfo
        //
        // Extract the map description from the .mis file
        //------------------------------------------------------------------------------

        public static void BuildLoadInfo(string mission)
        {
            //Replaced the torque file stuff w/ csharp, less stuff inside of torque.
            ClearLoadInfo();
            string missionpath = Path.GetDirectoryName(Directory.GetCurrentDirectory()) + "\\" + mission.Replace("/", "\\");
            if (File.Exists(missionpath))
                {
                string infoObject = "";
                using (StreamReader sr = new StreamReader(missionpath))
                    {
                    bool inInfoBlock = false;
                    while (sr.Peek() >= 0)
                        {
                        string line = sr.ReadLine();
                        if (line.Trim().StartsWith("new ScriptObject(MissionInfo) {"))
                            inInfoBlock = true;
                        if (line.Trim().StartsWith("new LevelInfo(theLevelInfo) {"))
                            inInfoBlock = true;
                        else if (inInfoBlock && line.Trim().StartsWith("};"))
                            {
                            inInfoBlock = false;
                            infoObject += line;
                            break;
                            }
                        if (inInfoBlock)
                            infoObject += line + " ";
                        }
                    }
                omni.console.Eval(infoObject);
                }
            else
                omni.console.error(string.Format("Level File {0} not found.", mission));
        }
Example #27
0
        public static List<Customer> GetCustomers()
        {
            // if the directory doesn't exist, create it
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            // create the object for the input stream for a text file
            StreamReader textIn =
                new StreamReader(
                    new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));

            // create the array list for customers
            List<Customer> customers = new List<Customer>();

            // read the data from the file and store it in the ArrayList
            while (textIn.Peek() != -1)
            {
                string row = textIn.ReadLine();
                string[] columns = row.Split('|');
                Customer customer = new Customer();
                customer.FirstName = columns[0];
                customer.LastName = columns[1];
                customer.Email = columns[2];
                customers.Add(customer);
            }

            textIn.Close();

            return customers;
        }
Example #28
0
        /// <summary>
        /// Initializes a new instance of the CircleOfTrust class.
        /// </summary>
        /// <param name="fileName">The file used to initiliaze this class.</param>
        public CircleOfTrust(string fileName)
        {
            try
            {
                this.Attributes = new NameValueCollection();

                StreamReader streamReader = new StreamReader(File.OpenRead(fileName));
                char[] separators = { '=' };
                while (streamReader.Peek() >= 0)
                {
                    string line = streamReader.ReadLine();
                    string[] tokens = line.Split(separators);
                    string key = tokens[0];
                    string value = tokens[1];
                    this.Attributes[key] = value;
                }

                streamReader.Close();
            }
            catch (DirectoryNotFoundException dnfe)
            {
                throw new CircleOfTrustException(Resources.CircleOfTrustDirNotFound, dnfe);
            }
            catch (FileNotFoundException fnfe)
            {
                throw new CircleOfTrustException(Resources.CircleOfTrustFileNotFound, fnfe);
            }
            catch (Exception e)
            {
                throw new CircleOfTrustException(Resources.CircleOfTrustUnhandledException, e);
            }
        }
Example #29
0
 static void Main(string[] args)
 {
     if (args.Length < 2 || !File.Exists(args[0]) || !Directory.Exists(args[1]))
     {
         printUsage();
         return;
     }
     string foldersListConfigFile = args[0];
     string destinationFolder = args[1];
     logFilePath = destinationFolder + @"/log.txt";
     indexRecord = new IndexRecord(destinationFolder);
     using (StreamReader reader = new StreamReader(foldersListConfigFile))
     {
         while (reader.Peek() >= 0)
         {
             string folder = reader.ReadLine();
             if (folder.StartsWith("-"))
                 notScanFolderList.Add(folder.Remove(0, 1));
             else
                 scanFolderList.Add(folder);
         }
     }
     foreach (string folder in scanFolderList)
     {
         Console.WriteLine("Start Scan Folder: " + folder);
         recordAllFileInfo(folder, destinationFolder);
     }
     indexRecord.scanCleanAndGenerateFileIDToDeleteList(destinationFolder + @"\delete");
     indexRecord.saveFileIDIndexedList();
     Console.WriteLine("Done! File Processed: {0}; Directory Processed: {1}; Directory Skipped: {2}; Error: {3}", processedFileCount, processedDirectoryCount, skippedDirectoryCount, errorCoult);
 }
Example #30
0
 public static void AnalyzeSimilarLines()
 {
     // Convert all .txt file to .dat files
     string[] inFiles = Directory.GetFiles(hydro.getDataDirectory() + @"\wspro88\", "*.DAT");
     foreach (string f in inFiles)
     {
         using (StreamReader sr = new StreamReader(f))
         {
             //System.Collections.Hashtable streamHash = new System.Collections.Hashtable();
             while (sr.Peek() >= 0)
             {
                 string line = sr.ReadLine();
                 string key = "";
                 if (line.Length <= 2) key = line;
                 else key = line.Substring(0, 2);
                 key.Trim();
                 if (key.Length > 0 && key.IndexOf('*') == -1)
                 {
                     string filename = hydro.getDataDirectory() + @"\wspro88\" + key + "_Summary.in";
                     using (StreamWriter sw = new StreamWriter(filename, true))
                     {
                         sw.WriteLine(line);
                     }
                 }
             }
         }
         GC.Collect();
     }
 }