File Shredder Code Sample (C# 4.0)

It has been a while since I last posted a code sample. So here is one for you guys to take a look at. Below is the file/directory shredder class.

class FileUtilities
{
    private static Random Randomizer = new Random();

    public static bool Shred(string directoryPath, bool shouldDelete = true)
    {
        bool success = true;
        try
        {
            string[] files = Directory.GetFiles(directoryPath, "*", SearchOption.AllDirectories);
            foreach (string file in files)
                success &= FileUtilities.ShredFile(file, shouldDelete);

            string[] directories = Directory.GetDirectories(
                directoryPath,
                "*",
                SearchOption.AllDirectories
            ).OrderByDescending(
                str =>
                str.Split('\\').Length - 1
            ).ToArray();
            foreach (string directory in directories)
                success &= FileUtilities.ShredDirectory(directory, shouldDelete);

            success &= FileUtilities.ShredDirectory(directoryPath, shouldDelete);
        }
        catch
        {
            success = false;
        }
        return success;
    }

    public static bool ShredDirectory(string directoryPath, bool shouldDelete = true)
    {
        bool success = true;
        try
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);

            string[] directoryBits = directoryPath.Split('\\');
            directoryBits[directoryBits.Length - 1] = FileUtilities.RandomName(directoryInfo.Name.Length);

            string newDirectoryPath = String.Join("\\", directoryBits);
            directoryInfo.MoveTo(newDirectoryPath);

            if (shouldDelete)
                directoryInfo.Delete();
        }
        catch
        {
            success = false;
        }
        return success;
    }

    public static bool ShredFile(string filePath, bool shouldDelete = true)
    {
        bool success = true;
        try
        {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Write);
            for (long i = 0; i < fs.Length; i++)
                fs.WriteByte((byte)Randomizer.Next(0, 255));

            fs.Close();

            FileInfo fileInfo = new FileInfo(filePath);
            fileInfo.MoveTo(fileInfo.DirectoryName + @"\" + FileUtilities.RandomName(fileInfo.Name.Length));

            if (shouldDelete)
                fileInfo.Delete();
        }
        catch
        {
            success = false;
        }
        return success;
    }

    private static string RandomName(int length)
    {
        string fileNameChars = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ~!@¤#$£§%^&()+`={}][;,";
        string newFileName = String.Empty;
        for (int i = 0; i < length; i++)
            newFileName += fileNameChars[Randomizer.Next(0, fileNameChars.Length)];

        return newFileName;
    }
}

The usage calls for these functions as as follows:

bool success = FileUtilities.Shred(@"D:\Temp"); // This method will recursively shred a file / folder.
bool success = FileUtilities.ShredDirectory(@"D:\Temp"); // This method will shred the contents of a folder and the root folder.
bool success = FileUtilities.ShredFile(@"D:\Temp\test.txt"); // This method will shred a specified file.[

I will not go through the code line-by-line to explain it as I feel most of the code is pretty self-explanatory. However if there are any questions feel free to post a comment.

CSIT and Network Information

Hi guys!

Network information is a complex subject at the best of times and simplifying it for the average user is no simple feat. Even harder it seems is actually writing code to get this information programatically! I was quite disappointed to find that there was no simple way to get an IP address via code – mainly since Windows does not actually know it until a request is made. I eventually made a work around and used a web script to scrape the information. It saved a lot of time and effort in the end.

Getting the internal IP address was also quite interesting. It involved using some built-in .NET code. The only issue is that there were nearly always IPv6 addresses returned first. Since these are not well known (yet) I decided to list only the IPv4 address instead. The code I came up with is listed below – hopefully it will help someone else.

1
2
IPHostEntry localIPAddresses = Dns.GetHostEntry(Dns.GetHostName());
string localIP = (from ip in localIPAddresses.AddressList where (ip.AddressFamily == AddressFamily.InterNetwork) select ip).First().ToString();

As you can see I also use LINQ there instead of a foreach loop since I find it much more readable. I am nearly finished with the main basic info page now so pretty soon I will have some new screen shots to demonstrate the new design of CSIT!

Calling the __cpuid MSVC function via C# a DLL Pinvoke (C++, C#)

Here is the latest piece of code I wish to share with everyone since I run into this myself, I am sure others will be interested also.

The C++ Part

Firstly you will need to create a new DLL project in Visual Studio. You will also need to add this line into the cpp file for your project:

1
#include <intrin.h>

This will allow you to access the intrinsic __cpuid call.

Next, I use a custom structure to hold the data returned by the function call. I do this mainly for readability since it helps when referencing. The code for the structure is as follows and should be added to the header file.

1
2
3
4
5
6
7
struct CPUInfo
{
    int EAX;
    int EBX;
    int ECX;
    int EDX;
};

Simple enough eh? Good. Now we need to construct a function call that will wrap the results from a __cpuid call into the structure above. Again, this is quite simple:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
extern "C" __declspec(dllexport) CPUInfo cpuID(int infoType)
{
    CPUInfo i;
    int results[4] = { 0, 0, 0, 0 };
    __try
    {
        __cpuid(results, infoType);
    }
    __except (EXCEPTION_EXECUTE_HANDLER) {}

    i.EAX = results[0];
    i.EBX = results[1];
    i.ECX = results[2];
    i.EDX = results[3];

    return i;
}

Finally you will need the following function definition for the header file:

1
extern "C" __declspec(dllexport) CPUInfo cpuID(int infoType);

As you can see. The above function also checks for any exceptions – it needs this as some older CPUs do not support the cpuid call. In these cases it will simply return a CPUInfo structure filled with 0’s so that the code doesn’t break anything.

Now. You will need to compile the DLL and then you can use it in your C# project using the following method.

The C# Part

First. Create an analogue of the C++ CPUInfo class in C#. This is really simple to do and the following is what is needed, for those who do not wish to try themselves:

1
2
3
4
5
6
7
8
[StructLayout(LayoutKind.Sequential)]
struct CPUInfo
{
    public int EAX;
    public int EBX;
    public int ECX;
    public int EDX;
}

Finally you will need the pinvoke definition. Depending on the name of the DLL (I called mine HardwareInfo.dll) the following code will be slightly different:

1
2
3
4
5
6
7
/// <summary>
/// This pinvoke method will return the result from a __cpuid call, if supported.
/// </summary>
/// <param name="infoType">A code that indicates what information this instruction retrieves.</param>
/// <returns>A CPUInfo structure giving the result from the query, or an empty structure if not supported.</returns>
[DllImport("HardwareInfo.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern CPUInfo _cpuid(uint infoType);

Hopefully that wasn’t too bad. Here is an example of how you would use the above code:

1
2
CPUInfo example = cpuID(0x00000000);
uint maxSupportedStandardLevels = (uint)(example.EAX & 0xffff);

The above code will tell you the maximum supported level of call that is supported on the current processor.

Notes:

Just remember that you will need to add a reference to the System.Runtime.InteropServices namespace if you are going to use this code.

As always, comments, improvements and suggestions are welcome.

First Code Snippet – Simple Hertz and Bytes Converters (C#)

Hi everyone!

These are my first code snippets. These were written as part of my CSIT project and are used to convert sizes and frequencies easily from one type to another. First lets look at the byte conversion function.

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
public enum ByteUnits : int
{
    B,
    kB,
    MB,
    GB,
    TB,
    PB
}

public static string Bytes2Size(double value, ByteUnits fromType = ByteUnits.B)
{
    // If the bytes are 0 then we can logically go no further.
    if (value == 0)
    {
        return "0 B";
    }

    // First we need to convert the value back into the smallest unit.
    double from = (value * Math.Pow(1024, (double)fromType));

    // This will give us the index of the best size to use.
    double exponent = Math.Floor(Math.Log(from) / Math.Log(1024));

    // Return the processed value.
    return (from / Math.Pow(1024, exponent)).ToString("n2") + " " + Enum.GetName(typeof(ByteUnits), (int)exponent);
 }

As you can see the code above is relatively simple. Here is a a basic description of the process:

  1. lines 9 – 11 do a check to ensure that no 0’s fall into the function. Since, if they did, it would break the result.
  2. Line 15 converts the original value into the most basic unit that this type supports. In the case of the example above it converts the value back into bytes.
  3. Line 18 gathers the exponent. This will represent the index of the enumeration that the value should be converted into (basically anyway).
  4. Line 21 converts the value and then adds the symbol thanks to some .NET magic, then returns the result.

As you can see, these are pretty simple. They just contain the sets of units to be used in the conversions. One of the best features of this approach is that you simply need to add the symbol for the next unit to be able to translate to that higher unit. Simple no? I also promised you a version of the above function that converts the hertz unit – so here it is.

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
public enum HertzUnits : int
{
    Hz,
    KHz,
    MHz,
    GHz,
    THz,
    PHz
}

public static string Hertz2Frequency(double value, HertzUnits fromType = HertzUnits.Hz)
{
    // If the bytes are 0 then we can logically go no further.
    if (value == 0)
    {
        return "0 Hz";
    }

    // Get the original value.
    double from = (value * Math.Pow(1000, (double)fromType));

    // This will give us the index of the best size to use.
    double exponent = Math.Floor(Math.Log(from) / Math.Log(1000));

    // Return the processed value.
    return (from / Math.Pow(1000, exponent)).ToString("n2") + " " + Enum.GetName(typeof(HertzUnits), (int)exponent);
}

I hope you enjoyed this snippet. If you have anything you wish to say or suggest feel free to comment.