-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileAccess.cs
More file actions
82 lines (79 loc) · 2.98 KB
/
FileAccess.cs
File metadata and controls
82 lines (79 loc) · 2.98 KB
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
using System.IO;
using System.Runtime.CompilerServices;
namespace Useful
{
/// <summary>
/// This class contains some generic methods that could be used in several programs without being edited.
/// </summary>
public class UsefulFileAccess
{
/// <summary>
/// Read data from a file. This works
/// </summary>
/// <param name="filename">The name of the file to read.</param>
/// <returns>List containing the lines in the file.</returns>
/// <exception cref="Exception">Any errors are thrown up to be dealty with.</exception>
public static List<string> ReadFromFile(string filename)
{
List<string> rows = new List<string>();
try
{
if (File.Exists(filename))
{
using (StreamReader reader = new StreamReader(filename))
{
string line;
while ((line = reader.ReadLine()) != null)
{
rows.Add(line);
}
}
}
else
{
throw new Exception(String.Format("Reading exception: {0} does not exist", filename));
}
}
catch (FileNotFoundException fnfe)
{
throw new Exception("Exception thrown: " + fnfe.Message);
}
catch (IOException ioe)
{
throw new Exception("Exception thrown: " + ioe.Message);
}
return rows;
}
/// <summary>
/// Overwrite the data in the file with the supplied data.
/// </summary>
/// <param name="filename">The file to be written to.</param>
/// <param name="data">The data to be written to the file.</param>
public static void WriteToFile(string filename, string data)
{
UsefulFileAccess.WriteToFile(filename, data, true);
}
/// <summary>
/// Write data to the specified file. The contents of the file can be overwritten or appended to as
/// required.
/// </summary>
/// <param name="filename">The file to be written to.</param>
/// <param name="data">The data to be written to the file.</param>
/// <param name="append">Data will be appended if this is true, else data will be overwritten.</param>
/// <exception cref="Exception">Any errors are thrown up to be dealt with.</exception>
public static void WriteToFile(string filename, string data, bool append)
{
try
{
using (StreamWriter writer = new StreamWriter(filename, append))
{
writer.Write(data);
}
}
catch (IOException ioe)
{
throw new Exception("Exception thrown: " + ioe.Message);
}
}
}
}