Saturday, May 30, 2009

Size of Folder in Bytes (Deep or Shallow)

using System;
using System.IO;

public class Folder {
private static double sizeInBytes;

public static double Size(string directory, bool deep) {
DirectoryInfo dir = new DirectoryInfo(directory);
foreach(FileInfo f in dir.GetFiles()) {
sizeInBytes += f.Length;
}
if(deep) {
foreach(DirectoryInfo d in dir.GetDirectories()) {
Size(d.FullName, deep);
}
}
return sizeInBytes;
}

static void Main() {
Console.WriteLine("The total folder size in bytes is {0}", Folder.Size(@"c:\sonysys", true));
}
}

Ini File class

using System;
using System.Collections.Generic;
using System.Text;

//This namespace is for easy INI reading ad writing, designed to be practically errorless, you dont need to worry about things like if .exists .add .set etc, just .set
//XML is similar to INI, but not as simple and easily modified by humans
//INI is ideal for server settings etc.

//any keys found NOT under a group header will be put in group MAIN

//WARNING: THIS INI FILE DOES NOT SUPPORT COMMENTS
//FORMAT IS AS FOLLOWS:
//[GROUP]
//item1=True
//item2=some text here
//[GROUP2]
//soemthing=3
using System.IO;
namespace EasyINI
{
//A class to handle all file IO for multiple savable settings
//This class will create on-demand, an INI file of settings, keys need not be added before being assigned
public class INIFile
{
//this class handles the saving and loading of the file
protected string fname;
protected List inigroupnames;
protected List inigroups;

public INIFile(string @filename)
{
fname = filename;
inigroups = new List();
inigroupnames = new List();
reloadFile();
}

public INIGroup Group(string name)
{
name = name.ToUpper();
int i = inigroupnames.IndexOf(name);
if (i == -1)
{
return null;
}
else
{
return inigroups[i];
}
}

public void setValue(string group, string key, string value)
{
addGroup(group); //create the group (if not already existing)
Group(group).setValue(key, value); //set the value
}

public string getValue(string group, string key)
{
group = group.ToUpper();
key = key.ToLower();
if (inigroupnames.IndexOf(group) == -1)
{
return string.Empty;
}
else
{
return Group(group).getValue(key);
}
}

public void addGroup(string group)
{
group = group.ToUpper();
if (inigroupnames.IndexOf(group) == -1)
{
inigroupnames.Add(group);
inigroups.Add(new INIGroup(this));
}
}

public bool saveFile() //bool returned indicates the success of the save process
{
try
{
FileStream strm = new FileStream(fname, FileMode.Create, FileAccess.Write);
StreamWriter W = new StreamWriter(strm);
if(inigroupnames.Count > 0)
{
for (int i = 0; i < inigroupnames.Count; i++)
{
INIGroup grp = inigroups[i];
if (grp.getCount() > 0) //only save this group if it has content
{
W.WriteLine("[" + inigroupnames[i] + "]");
for (int k = 0; k < grp.getCount(); k++)
W.WriteLine(grp.getKey(k) + @"=" + grp.getValue(k));
W.WriteLine(" ");
}
}
}
W.Close();
strm.Close();
return true;
}
catch
{
return false;
}
}

public void reloadFile()
{
inigroups.Clear();
inigroupnames.Clear();

if (File.Exists(fname))
{
string strline;
string currentGroup = "MAIN";
FileStream strm = new FileStream(fname, FileMode.Open, FileAccess.Read);
StreamReader R = new StreamReader(strm);
while (R.EndOfStream != true)
{
strline = R.ReadLine(); //get line
if (strline.StartsWith("["))
{
//this is a group header
currentGroup = strline.Substring(1, strline.Length - 2);
}
else
{
//this is a key=value entry
string[] keyval = strline.Split('=');
if (keyval.Length == 2)
setValue(currentGroup, keyval[0], keyval[1]);
}
}
R.Close();
strm.Close();
}
}
}

//This sub-class is used by the INIFile class, it handles the keys and values within an INI group
public class INIGroup
{
//this class handles the settings of values
protected INIFile owner;
public List inikeys;
public List inivalues;
public INIGroup(INIFile parent)
{
owner = parent;
inikeys = new List();
inivalues = new List();
}

public void setValue(string key, string value)
{
key = key.ToLower();
int i = inikeys.IndexOf(key);
if (i == -1)
{
inikeys.Add(key);
inivalues.Add(value);
}
else
{
inivalues[i] = value;
}
owner.saveFile();
}

public string getValue(string key)
{
key = key.ToLower();
int i = inikeys.IndexOf(key);
if (i == -1)
{
return string.Empty;
}
else
{
return inivalues[i];
}
}

public string getKey(int index)
{
if (index > -1 && index < getCount())
{
return inikeys[index];
}
else
{
//out of range
throw new IndexOutOfRangeException("Index was out of range, must be non-negative and less than total key count");
}
}

public string getValue(int index)
{
if (index > -1 && index < getCount())
{
return inivalues[index];
}
else
{
//out of range
throw new IndexOutOfRangeException("Index was out of range, must be non-negative and less than total key count");
}
}

public int getCount()
{
return inikeys.Count;
}

}
}

Browse For Folder in .NET 1.0

//Have To Reference System.Design.dll

/*
Usage:
-
BrowseForFolder browse = new BrowseForFolder();
string savePath = browse.Show();
*/

using System;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace iCode_Library.NET
{

public class BrowseForFolder: FolderNameEditor
{

FolderNameEditor.FolderBrowser dirBrowser;
public BrowseForFolder()
{
dirBrowser = new FolderNameEditor.FolderBrowser();
}
public string Show()
{
//set the Description label
dirBrowser.Description = "Select Folder";
dirBrowser.ShowDialog(); //show the Windows
return dirBrowser.DirectoryPath + @"\"; // return whatever path choosen
}

}
}

File Content To Array

private ArrayList fileContentToArrayList(string filePath)
{

System.Collections.ArrayList arrListLines = new System.Collections.ArrayList();
//read the file content one by one
try
{
StreamReader fl = new StreamReader(filePath, System.Text.Encoding.ASCII);
//StreamReader fl = File.OpenText(filePath,);
string line = "";
while((line = fl.ReadLine()) != null )
{
arrListLines.Add(line);
}


}
catch(Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message, "Failed reading file");
return null;
}
return arrListLines;
}

Reading a text file with StreamReader

// Reading a text file with StreamReader

private void ImportCountries()
{
string delimiter = ",";
string fileName = @"c:\countrylist3.csv";

StreamReader sr = new StreamReader(fileName);

try
{
while (sr.Peek() >= 0)
{
string r = sr.ReadLine();
string[] items = r.Split(delimiter.ToCharArray());
}
}
finally
{
sr.Close();
}
}

Write file to response stream

// Wrtites temporary file to response stream and then delete

Response.Clear();
Response.ContentType = "image/tiff";
Response.AddHeader("Content-Disposition", "attachment; filename=imageFile.tiff");
Response.WriteFile(tempPath);
Response.Flush();
Response.Close();

if(File.Exists(tempPath))
{
File.Delete(tempPath);
}

Short/Long path conversion

// Short/Long path conversion

// Long To Short Path/File Name:

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetShortPathName(
[MarshalAs(UnmanagedType.LPTStr)] string path,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder shortPath,
int shortPathLength
);

// ...

StringBuilder shortPath = new StringBuilder(1024);
GetShortPathName(textBoxFilename.Text, shortPath, shortPath.Capacity);



// Short To Long Path/File Names:

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetLongPathName(
[MarshalAs(UnmanagedType.LPTStr)]
string path,
[MarshalAs(UnmanagedType.LPTStr)]
StringBuilder longPath,
int longPathLength
);