3
3
using System . Collections . Generic ;
4
4
using System . IO ;
5
5
using System . Reflection ;
6
+ using System . Text ;
6
7
7
8
namespace DataStructures . Common
8
9
{
@@ -22,7 +23,6 @@ public sealed class PrimesList
22
23
23
24
//
24
25
// INSTANCE VARIABLES
25
- private static string _primesDocPath = string . Empty ;
26
26
private readonly static List < int > _primes = new List < int > ( ) ;
27
27
28
28
// 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
49
49
{
50
50
if ( _instance == null )
51
51
{
52
- _instance = new PrimesList ( ) ;
53
52
_initializeData ( ) ;
53
+ _instance = new PrimesList ( ) ;
54
54
}
55
55
}
56
56
}
@@ -64,10 +64,9 @@ public static PrimesList Instance
64
64
/// </summary>
65
65
private static void _initializeData ( )
66
66
{
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" ) ;
69
68
70
- foreach ( var line in lines )
69
+ foreach ( var line in lines )
71
70
{
72
71
// Split the line by commas and convert the collection to a list.
73
72
var numbersAsStrings = line . Split ( ',' ) . ToList < string > ( ) ;
@@ -77,9 +76,16 @@ private static void _initializeData()
77
76
78
77
if ( numbersAsStrings . Count > 0 )
79
78
{
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
+ }
83
89
}
84
90
}
85
91
}
@@ -209,6 +215,22 @@ public void CopyTo(int[] array, int index = 0)
209
215
}
210
216
}
211
217
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
+ }
212
235
}
213
-
214
236
}
0 commit comments