Skip to content

Instantly share code, notes, and snippets.

@kyrathasoft kyrathasoft/MyFiles.cs
Last active Aug 29, 2015

Embed
What would you like to do?
Demonstrates: (1) converting file size (number of bytes) to string description, e.g., "7.405 Kb" (2) reading a file into an array of type byte (3) writing string data to a filepath (4) returning number of files in given directory matching a given pattern (5) returning total size of those pattern-matched files, in bytes (6) obtaining the director…
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using com.williambryanmiller.strings;
using com.williambryanmiller.testing;
namespace com.williambryanmiller.files {
class MyFiles {
/* Note: this class file is also found on GitHub Gist
* @ https://gist.github.com/kyrathasoft/e0dc96b13679ff452139 */
public static bool appearsToBePureAsciiFile(string pathToFile) {
bool test = true;
string filepath = pathToFile;
using (StreamReader sr = new StreamReader(filepath)) {
string text = sr.ReadToEnd();
if (MyTests.appearsToBePureAscii(text)) {
//test remains 'true'
} else {
test = false;
}
}
return test;
}
public static string getFilesizeDesc(double sizeInBytes) {
const double Terabyte = 1099511627776;
const double Gigabyte = 1073741824;
const double Megabyte = 1048576;
const double Kilobyte = 1024;
if (sizeInBytes < Kilobyte) {
return ((sizeInBytes).ToString() + " bytes");
}
if ((sizeInBytes >= Kilobyte) && sizeInBytes < Megabyte) {
return (((sizeInBytes / Kilobyte).ToString("N3") + " Kb"));
}
if((sizeInBytes >= Megabyte) && sizeInBytes < Gigabyte){
return (((sizeInBytes/Megabyte).ToString("N3") + " Mb"));
}
if ((sizeInBytes >= Gigabyte) && sizeInBytes < Terabyte) {
return ((sizeInBytes / Gigabyte).ToString("N3") + " Gb");
}
if (sizeInBytes >= Terabyte){
return ((sizeInBytes/Terabyte).ToString("N3") + " Tb");
}
return "0 bytes";
}
public static bool wroteStringToTextFile(string s, string filepath) {
bool test = false;
try {
FileInfo fi = new FileInfo(filepath);
StreamWriter sw = fi.CreateText();
sw.Write(s);
sw.Close();
sw.Dispose();
test = true;
} catch (Exception ex) {
//you could use either Console.Write() or a message box, depending
//on whether you're using this method in a Console or WinForms app
}
return test;
}
public static string readAsciiFileIntoString(string filepath) {
string p = string.Empty;
using (StreamReader sr = new StreamReader(filepath)) {
p = sr.ReadToEnd();
}
return p;
}
public static byte[] ReadByteArrayFromFile(string fileName) {
byte[] buff = null;
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long numBytes = new FileInfo(fileName).Length;
buff = br.ReadBytes((int)numBytes);
return buff;
}
public static long returnTotalBytesOfFilesMatchingPattern(string _directory, string _pattern) {
long total = 0;
if (!Directory.Exists(_directory)) { return -1; }
DirectoryInfo di = new DirectoryInfo(_directory);
FileInfo[] fi = di.GetFiles(_pattern);
foreach (FileInfo f in fi) {
total += f.Length;
}
return total;
}
public static int returnNumFilesMatchingPattern(string _directory, string _pattern) {
//finds and returns the number of files in given directory matching the pattern
//if dir passed as first parameter doesn't exist, return -1
if (!Directory.Exists(_directory)) { return -1; }
int cnt = 0;
DirectoryInfo di = new DirectoryInfo(_directory);
FileInfo[] fi = di.GetFiles(_pattern);
foreach (FileInfo f in fi) {
cnt++;
}
return cnt;
}
public static string dirOfExecutingAssembly() {
return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
}
public static bool createdAppSubdirectoryIfItDoesntExist(string subdir) {
bool test = false;
string myDir = dirOfExecutingAssembly() + "\\" + subdir + "\\";
if (!Directory.Exists(myDir)) {
try {
Directory.CreateDirectory(myDir);
test = true;
} catch (Exception ex) {
}
}
return test;
}
public static bool serializedToDiskInBinary(string filepath, object o) {
bool success = true;
FileStream fStream = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
try {
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(fStream, o);
} catch (Exception serEx) {
success = false;
Console.WriteLine(serEx.Message);
} finally {
if (fStream != null) {
fStream.Close();
}
}
return success;
}
public static object deserializeObjectFromDiskToMemory(string filepath) {
object myObj = null;
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.None);
try {
BinaryFormatter bFormatter = new BinaryFormatter();
myObj = (object)bFormatter.Deserialize(fs);
} catch (Exception deserEx) {
Console.WriteLine(deserEx.Message);
} finally {
if (fs != null) {
fs.Close();
}
}
return myObj;
}
public static long returnFileLength(string p) {
if (!System.IO.File.Exists(p)) {
return -1;
} else {
FileInfo fi = new FileInfo(p);
return fi.Length;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.