33using System . Collections . Generic ;
44using System . IO ;
55using System . Reflection ;
6+ using System . Text ;
67
78namespace DataStructures . Common
89{
@@ -22,7 +23,6 @@ public sealed class PrimesList
2223
2324 //
2425 // INSTANCE VARIABLES
25- private static string _primesDocPath = string . Empty ;
2626 private readonly static List < int > _primes = new List < int > ( ) ;
2727
2828 // Picked the HashPrime to be (101) because it is prime, and if the ‘hashSize - 1’ is not a multiple of this HashPrime, which is
@@ -49,8 +49,8 @@ public static PrimesList Instance
4949 {
5050 if ( _instance == null )
5151 {
52- _instance = new PrimesList ( ) ;
5352 _initializeData ( ) ;
53+ _instance = new PrimesList ( ) ;
5454 }
5555 }
5656 }
@@ -64,10 +64,9 @@ public static PrimesList Instance
6464 /// </summary>
6565 private static void _initializeData ( )
6666 {
67- _primesDocPath = Path . Combine ( Path . GetDirectoryName ( typeof ( PrimesList ) . GetTypeInfo ( ) . Assembly . Location ) , @"Data/PrimesDocument_10K.csv" ) ;
68- string [ ] lines = File . ReadAllLines ( _primesDocPath ) ;
67+ string [ ] lines = _readResource ( "DataStructures.Data.PrimesDocument_10K.csv" ) ;
6968
70- foreach ( var line in lines )
69+ foreach ( var line in lines )
7170 {
7271 // Split the line by commas and convert the collection to a list.
7372 var numbersAsStrings = line . Split ( ',' ) . ToList < string > ( ) ;
@@ -77,9 +76,16 @@ private static void _initializeData()
7776
7877 if ( numbersAsStrings . Count > 0 )
7978 {
80- // cast them into integers and add them to the primes list
81- var numbers = numbersAsStrings . Select ( item => Convert . ToInt32 ( item ) ) . ToList < int > ( ) ;
82- _primes . AddRange ( numbers ) ;
79+ try
80+ {
81+ // cast them into integers and add them to the primes list
82+ var numbers = numbersAsStrings . Select ( item => Convert . ToInt32 ( item ) ) . ToList < int > ( ) ;
83+ _primes . AddRange ( numbers ) ;
84+ }
85+ catch ( Exception e )
86+ {
87+ throw new Exception ( line . Replace ( "\r " , "{\\ r}" ) . Replace ( "\n " , "{\\ n}" ) , e ) ;
88+ }
8389 }
8490 }
8591 }
@@ -209,6 +215,22 @@ public void CopyTo(int[] array, int index = 0)
209215 }
210216 }
211217
218+ /// <summary>
219+ /// Reads an embedded resource as a text file.
220+ /// </summary>
221+ /// <returns></returns>
222+ private static string [ ] _readResource ( string resourceName )
223+ {
224+ try
225+ {
226+ using ( var stream = typeof ( PrimesList ) . GetTypeInfo ( ) . Assembly . GetManifestResourceStream ( resourceName ) )
227+ using ( var reader = new StreamReader ( stream ?? throw new InvalidOperationException ( "Failed to read resource" ) , Encoding . UTF8 ) )
228+ return reader . ReadToEnd ( ) . Split ( "\n " ) ;
229+ }
230+ catch ( Exception ex )
231+ {
232+ throw new Exception ( $ "Failed to read resource { resourceName } ", ex ) ;
233+ }
234+ }
212235 }
213-
214236}
0 commit comments