-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileHandler.cs
93 lines (81 loc) · 2.79 KB
/
FileHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
namespace Sudoku
{
class FileHandler
{
static public char[,] GetSudokuGrid()
{
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
var directory = System.IO.Path.GetDirectoryName(path);
var fileName = UI.GetFilenameFromUser("Enter file name to load: (ex: sudoku.txt)");
List<string> sudokuRows = new List<string>();
try {
using (StreamReader reader = new StreamReader(directory + @"\" + fileName))
{
while (!reader.EndOfStream)
{
sudokuRows.Add(reader.ReadLine());
}
}
var result = sudokuRows.Select(item => item.ToCharArray()).ToArray();
if(result.GetLength(0) == 9 && result[0].Length == 9)
{
return JaggedArrayTo2D(result);
}
return new char[,] { };
}
catch
{
return new char[,] { };
}
}
static public bool PersistSudokuGrid(char[,] grid)
{
if (!UI.UserPromt())
{
return false;
}
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
var directory = System.IO.Path.GetDirectoryName(path);
var fileName = UI.GetFilenameFromUser("Enter file name to save: (ex: sudoku.txt)");
try
{
using (var writer = new StreamWriter(directory + @"\" + fileName))
{
for (int row = 0; row < grid.GetLength(0); row++)
{
for (int col = 0; col < grid.GetLength(1); col++)
{
writer.Write(grid[row, col]);
if (col == 8)
{
writer.WriteLine("");
}
}
}
}
return true;
}
catch
{
return false;
}
}
static char[,] JaggedArrayTo2D(char[][] jaggedArray)
{
char[,] result = new char[jaggedArray.Length, jaggedArray[0].Length];
for (int i = 0; i < jaggedArray.Length; i++)
{
for (int k = 0; k < jaggedArray[0].Length; k++)
{
result[i, k] = jaggedArray[i][k];
}
}
return result;
}
}
}