C#: 文件读取操作

来源:互联网 发布:vb.net label 透明 编辑:程序博客网 时间:2024/06/05 08:58

Question:

Ihave the following line within some code using StreamReader to "loop"through the reading of a file:

while((line = sr.ReadLine()) != null)

1. My question is this, is it possible to read only SPECIFIC lines of the inputfile?  So instead of looping through the entire file reading each line,perhaps I'd like to read only "line 55" or "line 72". Possible?

2. Also,if I may.  Is it possible to only certain character positions within aline?  So if a line in the file read: 

"FirstNumber is 127.4  Second Number is 42.6"

canI read ONLY the numeric values (127.4 AND 42.6)?  Thank you in advance.


Now I am answering your firstquestion.

I write a while loop body such as:

while((line=sr.ReadLine())!=null)      {      counter++;        if(counter>=55&&counter<=72)            System.Console.WriteLine(line);       }


At the beginning, I wrote belowinstand of ablove:

while((line=sr.ReadLine())!=null)

                              {

                                               if(counter>=55&&counter<=72)                               /**

                                                              System.Console.WriteLine(line);                      A**/

                                              counter++;                                                                        /**B**/

                              }

I have saw it led to a mistake: itoutput line 56 to line 73, so I exchange the sequence of A and B to correctthis mistake.

I have completed your secondquestion. You can open theattach file to readit.

My codes can Implement thefollowing feature:

“1.dfer234bvh3.785”à number:1, 234, 3.785

But if the line is like “dfgdg589.369.21”,I could only get the number: 589.369, “21” will be scrapped.




/*====================================== *  *  *  *          author: Shenxiang Huang *  *  * =======================================*/using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ReadFile{    class ReadFile    {        static void Main(string[] args)        {            List<double> numberList = new List<double>();            string line;            int lineCounter = 0;            string filepath = @"C:\test\sourcetext.txt";            System.IO.StreamReader sr = new System.IO.StreamReader(filepath);            while((line=sr.ReadLine())!=null)            {                int position = 0;                StringBuilder sb = new StringBuilder();                //change the string line to char Array                char[] chars = line.ToCharArray();                for (int i = 0; i < chars.Length; i++)                {                    char c = chars[i];                                        //if the character is between '0' and '9', it will be saved to stringBuilder:sb                    if(c>=48 && c<58)                    {                        sb.Append(c);                    }                    //if the character is '.'                    else if(c=='.')                    {                        if(sb.Length==0)                        {                            continue;                        }                        else if(sb.ToString().IndexOf('.',position)!=-1)                        {                            break;                        }                        else                        {                            sb.Append(c);                        }                    }                    else                    {                        if(sb.Length!=0)                        {                            //if there is two points '.' between two spaces ' ', remove the newest point '.'                            if (sb.ToString().IndexOf('.', sb.ToString().Length - 1) != -1)                                sb.Remove(sb.ToString().Length - 1,1);                            sb.Append(' ');//every number in stringBuilder is separated by space:' '.                            position = sb.Length;                                                        continue;                        }                    }                   }                                //Convert stringbuilder to string                string numberString = sb.ToString();                //split number with space ' '                string[] charsStringSplit = numberString.Split(' ');                //ierate array charStringSplit and convert string to double number, add to collection: numberList                foreach (string doub in charsStringSplit)                {                    if (doub.Equals(null))                        continue;                    try                    {                        double value = double.Parse(doub);                        numberList.Add(value);                    }                    catch (Exception e)                    { }                                    }                                Console.WriteLine("Line {0}: {1} ", ++lineCounter, sb);            }            sr.Close();            Console.WriteLine("\n-----------\n the numbers in {0} :",filepath);            //iterating over the collection: numberList to output numbers            int n = 0;            foreach (double d in numberList)            {                Console.Write(d+"  ");                n++;                if (n % 10 == 0)                    Console.WriteLine();            }            System.Console.ReadKey();        }    }}



0 0