Introduction
Read CSV Input from a text file, and add the integer values in each string read (Line by Line). Incorporate Unit Tests to test the program's functionality.
Background
I have been moving my development language of choice from VB.NET to C# .NET, and one of my most recent tasks has been to code a solution that reads line input from a CSV file with expected delimiters ";" and "," for each line. In my first attempt I got a very long solution, which was rough with errors upon trying to run the code. In the second attempt I shortened the code and made some good discoveries about the power of .NET and C#. So if you are having second
thoughts about moving from VB.NET to C# I guess this should be a good starting point.
Using the code
The code outlined in this article, is very simple. All you need is a .txt file with lines containing integers separated by commas "," or semi-colons ";" per line. The following sample
data should be helpful:
123,3455,55
1;3;44;555;66
1324,55
13,444
2345,444,555,44
23455;5675;66
Copy the above lines into your .txt file and save it in a location "DriveLetter:\FolderOfChoice\yourfileName.txt".
Start Visual Studio NB for this solution I used VS2010.
Create a new Console Application and name it accordingly e.g.,
StringCal
.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
Now add the following code between:
namespace StringCalc
{
}
namespace StringCalc
{
class Program
{
static string theLine; static int[] theList; static int LineNumber = 1; static int theSum; static StreamReader file = new StreamReader(
"DriveLetter:/[FolderOfYourChoice]/yourfileName.txt");
static void Main(string[] args)
{
while ((theLine = file.ReadLine()) != null)
{
Add(theLine); }
Console.ReadLine();
file.Close(); }
public static void Add(string numbers)
{
if (numbers.Contains(";")) {
theList = numbers.Split(';').Select(int.Parse).ToArray();
}
else if (numbers.Contains(",")) {
theList = numbers.Split(',').Select(int.Parse).ToArray(); ;
}
else
{
throw new ArgumentException();
}
theSum = theList.Sum();
Console.WriteLine("The sum of the numbers entered at line : " +
LineNumber.ToString() + " is : " + theSum);
LineNumber++;
}
}
}
I have not added instructions on the how to step by step, to those of you interested in checking the working solution simply download the attached completed solution
and create the text file then populate it with the sample data given at the beginning of this article.
The Unit Test Project
using IUAStringCalculator;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace StringCalc
{
[TestClass()]
public class ProgramTest
{
private TestContext testContextInstance;
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
#endregion
[TestMethod()]
[DeploymentItem("IUAStringCalculator.exe")]
public void AddTest()
{
string numbers = "1234,8594,945,99";
int expectedResult = 10872;
Program_Accessor.Add(numbers);
int theResult = Program_Accessor.theSum;
Assert.AreEqual(theResult, expectedResult);
}
[TestMethod()]
[DeploymentItem("IUAStringCalculator.exe")]
[ExpectedException(typeof(FormatException))]
public void AddTest_Must_Throw_FormatException()
{
string numbers = "1234;756hd;945;33";
Program_Accessor.Add(numbers);
}
}
}
Points of Interest
I found this little exercise extremely enjoyable, especially with the way the
<String>.Split(";").Select...
worked.
This saved a lot of long checks and validation on the string to integer conversion and passing the successful input to an array. Also note the use of the
Sum()
function
on the Array of integers.
In writing the Unit tests I had more fun especially when testing the Exception part of it. I actually learnt that you can test for any
occurrences
of a particular type of Exception and.
History
- Initial article and sample source code: 14/10/2013.