Results 1 to 4 of 4

Thread: [RESOLVED] Sum numbers in a textfile.

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Apr 2010
    Posts
    131

    Resolved [RESOLVED] Sum numbers in a textfile.

    I just got a textfile with a couple of numbers (1 number in one row), how would I sum these numbers? I thought it would be easy, but thing is it's turning out to be not so easy.

  2. #2
    Frenzied Member mickey_pt's Avatar
    Join Date
    Sep 2006
    Location
    Corner of the Europe :)
    Posts
    1,959

    Re: Sum numbers in a textfile.

    Read all lines of the file to an array, loop trough the array and add the numbers...

    vb.net Code:
    1. Dim total As Double = 0
    2. For Each line As String In IO.File.ReadAllLines("PATH_TO_FILE")
    3.    total += Double.Parse(line)
    4. Next
    5. MsgBox(String.Format("Sum={0}", total.ToString), MsgBoxStyle.Information)
    Last edited by mickey_pt; Feb 24th, 2011 at 09:31 AM. Reason: Code

    Rate People That Helped You
    Mark Thread Resolved When Resolved

  3. #3
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Sum numbers in a textfile.

    Try this:
    vb.net Code:
    1. Dim fileContents() As String = IO.File.ReadAllLines("C:\Temp\test.txt")
    2. Dim sum As Long = (From item In fileContents Select CLng(item)).Sum
    3. MsgBox(sum)
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Apr 2010
    Posts
    131

    Re: Sum numbers in a textfile.

    Both codes work perfectly, big thanks to you guys, really helped me.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width