C#: 文件读取操作

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 the attach 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值