Last active
August 29, 2015 13:55
-
-
Save bradjolicoeur/8710236 to your computer and use it in GitHub Desktop.
File Helper for working with files...will add more methods in the future.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.IO; | |
public static class FileHelper | |
{ | |
/// <summary> | |
/// Read the contents of a file and return as a string. | |
/// This method closes the file as soon as it has been read. | |
/// </summary> | |
/// <param name="fileName"></param> | |
/// <returns></returns> | |
public static string GetFileContents(string fileName) | |
{ | |
StringBuilder results = new StringBuilder(); | |
using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) | |
using (BufferedStream bs = new BufferedStream(fs)) | |
using (StreamReader sr = new StreamReader(bs)) | |
{ | |
string line; | |
while ((line = sr.ReadLine()) != null) | |
{ | |
results.AppendLine(line); | |
} | |
} | |
var what = results.ToString(); | |
return what; | |
} | |
/// <summary> | |
/// Writes string to file | |
/// </summary> | |
/// <param name="fileName">full file path and name</param> | |
/// <param name="content">string to be written to the file</param> | |
/// <param name="append">if true the file will be appended to. if false the file will be overwritten. default is false</param> | |
public static void WriteStringToFile(String fileName, String content, bool append = false) | |
{ | |
using (StreamWriter outfile = new StreamWriter(fileName, append)) | |
{ | |
outfile.Write(content); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment