IsraelTorres icon

sticky

IsraelTorres | PRO | 11/01/11 06:52:05 PM UTC | 0 ⭐ | 412 👁️ | Never ⏰ | []
C# |

10.57 KB

|

None

|

0 👍

/

0 👎

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
 
namespace sticky
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            doStuff();
        }
 
        //volume label to look for. could potentially have it read a text file or something
        private static List<string> validVolumeLabels = new List<string>(){ "helix3pro" };
        private static string uNetBootEXE = "unetbootin-windows-563.exe";
        private static string formatCommandTemplate = "format $DRIVELETTER /FS:FAT32 /V:helix3pro /Q /y";
        private static string unetbootParams =
        "method=diskimage isofile=\"$ISOFILE\" installtype=USB targetdrive=$DRIVELETTER nodistro=y exitoncompletion=y autoinstall=y";
 
        private static void doStuff()
        {
            //locate unetboot
            Console.WriteLine("Looking for unetbootin executable (" + uNetBootEXE + ") in " + Directory.GetCurrentDirectory() + " ...");
            if (!File.Exists(uNetBootEXE))
            {
                Console.WriteLine(uNetBootEXE + " not found in directory.");
                Console.ReadLine();
                Environment.Exit(0);
            }
 
            //identify the ISO
            //string isoFile = @"C:\VMWare_Share\helix3custom\Helix3ProR2Custom-v1_2011-10-27.iso";
            string isoFile = "";
 
            //Another example of locating your ISO file
 
            //IEnumerable<FileInfo> lwFi = new DirectoryInfo(@"\\foo\goase").GetFiles("*.iso", SearchOption.AllDirectories);
            //var lwQry = (from file in lwFi
            //             orderby file.LastWriteTime descending
            //             select file.FullName).SingleOrDefault();
 
            //isoFile = lwQry;
                
 
            Console.WriteLine("Searching \"" + Directory.GetCurrentDirectory() + "\" for ISO files...");
            DirectoryInfo di = new DirectoryInfo(Directory.GetCurrentDirectory());
            IEnumerable<FileInfo> fi = di.GetFiles();
            var isoQry = from file in fi
                         where file.Extension == ".iso"
                         select file.FullName;
 
            if (isoQry.Count() > 1)
            {
                Console.WriteLine("More than one ISO file found. I'm confused. Please fix and re-run program.");
                Console.ReadLine();
                Environment.Exit(0);
            }
            if (isoQry.Count() == 0)
            {
                Console.WriteLine("No ISO files found. I'm confused. Please fix and re-run program.");
                Console.ReadLine();
                Environment.Exit(0);
            }
 
            isoFile = isoQry.FirstOrDefault();
            
            Console.WriteLine("");
            Console.WriteLine("Using ISO: " + isoFile);
            Console.WriteLine("");
 
            //find the drives, confirm with user
            List<string> processTheseDrives = listDrivesToWipe(validVolumeLabels);
            if (processTheseDrives == null || processTheseDrives.Count == 0)
            {
                Console.WriteLine("No removable drives matching Volume Name Criteria were found!");
                Console.ReadLine();
                Environment.Exit(0);
            }
 
            //format drives FAT32
            Console.WriteLine("Okay, good. Starting wiping...");
            Console.WriteLine("");
            
 
            foreach (string driveLetter in processTheseDrives)
            {
                Console.WriteLine("Formatting drive " + driveLetter);
                //string formatCommand = @"format " + driveLetter.Replace(@"\", "") + " /FS:FAT32 /V:helix3pro /Q /y";
                string formatCommand = formatCommandTemplate.Replace("$DRIVELETTER", driveLetter.Replace(@"\", ""));
                ProcessStartInfo pInfo = new ProcessStartInfo("cmd.exe", "/c " + formatCommand);
                pInfo.RedirectStandardOutput = true;
                pInfo.UseShellExecute = false;
                pInfo.CreateNoWindow = true;
 
                Process P = new Process();
                P.StartInfo = pInfo;
                P.OutputDataReceived += exeOutputEventHandler;
                P.Start();
 
                P.BeginOutputReadLine();
                P.WaitForExit();
                P.Close();
                Console.WriteLine();
            }
 
            //run unetbootin
            Console.WriteLine("UNetBootin' ISO image to drives...");
            Console.WriteLine();
 
            foreach (string driveLetter in processTheseDrives)
            {
                Console.WriteLine("UNetBootin' drive " + driveLetter);
 
                Thread uNetBootThread = (new Thread(() =>
                                                        {
                                                            ProcessStartInfo p2info =
                                                                new ProcessStartInfo(uNetBootEXE,
                                                                                     unetbootParams.Replace(
                                                                                         "$DRIVELETTER", driveLetter).
                                                                                         Replace("$ISOFILE", isoFile));
 
                                                            p2info.RedirectStandardOutput = false;
                                                            p2info.UseShellExecute = true;
                                                            p2info.CreateNoWindow = false;
 
                                                            Process p2 = new Process();
                                                            p2.StartInfo = p2info;
                                                            p2.Start();
                                                            p2.WaitForExit();
                                                            p2.Close();
                                                        }) {Name = "UNetBootThread"});
                uNetBootThread.Start();
                while (uNetBootThread.IsAlive)
                {
                    //it's friday, friday, gotta get down on friday.
                }
 
            }
 
            Console.WriteLine("********** DONE **********");
 
            //Are we done?
            string exitProgram = "";
            while (exitProgram != "y" | exitProgram != "n" | exitProgram != "yes" | exitProgram != "no")
            {
                Console.Write("Done! Start a new batch? (or exit) [y/n]: ");
                exitProgram = Console.ReadLine().ToLower();
                if (exitProgram == "yes" || exitProgram == "y")
                {
                    doStuff();
                }
                else if (exitProgram == "no" || exitProgram == "n")
                {
                    return;
                }
            }
 
        }
 
        /// <summary>
        /// Checks logical drives for possible wipe/ISO targets
        /// </summary>
        /// <returns></returns>
        private static List<string> listDrivesToWipe(List<string> validVolumeLabels)
        {
            StringBuilder strValidLabels = new StringBuilder();
            foreach(string validLabel in validVolumeLabels)
            {
                strValidLabels.Append("\"" + validLabel + "\"" + " ");
            }
 
            Console.WriteLine("Searching for removable drives with volume labels containing: " + strValidLabels);
            List<DriveInfo> drivesAll = DriveInfo.GetDrives().ToList();
            List<string> drivesToProcess = new List<string>();
 
            Console.WriteLine("Listing possible target drives...");
            Console.WriteLine("");
            Console.WriteLine("Drive\tVolume Label\tFS\tType\t\tSize Info");
            Console.WriteLine("-----\t------------\t--\t----\t\t---------");
 
            foreach (var drv in drivesAll)
            {
                if (drv.IsReady)
                {
                    if (validVolumeLabels.Contains(drv.VolumeLabel, StringComparer.OrdinalIgnoreCase))
                    {
                        StringBuilder driveInformation = new StringBuilder();
                        driveInformation.Append(drv.Name);
                        driveInformation.Append("\t" + drv.VolumeLabel);
                        driveInformation.Append("\t" + drv.DriveFormat);
                        driveInformation.Append("\t" + drv.DriveType.ToString());
                        driveInformation.Append("\t" + bytesToGB(drv.AvailableFreeSpace).ToString("00.00"));
                        driveInformation.Append(" / ");
                        driveInformation.Append(bytesToGB(drv.TotalSize).ToString("00.00"));
                        driveInformation.Append(" GB");
 
                        Console.WriteLine(driveInformation.ToString());
                        drivesToProcess.Add(drv.Name);
                    }
                }
            }
            if (drivesToProcess.Count() == 0)
            {
                Console.WriteLine("No valid removable drives were found matching the volume label criteria.");
                Console.ReadLine();
                Environment.Exit(0);
            }
 
            Console.WriteLine("");
            Console.Write("Are these the correct drives? [y/n]");
            string usrInput = Console.ReadLine();
            if (usrInput.Trim().ToLower() != "y")
            {
                return null;
            }
 
            return drivesToProcess;
        }
 
        /// <summary>
        /// Convert bytes to GB
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        private static double bytesToGB(long bytes)
        {
            double ret = ((bytes/1024f)/1024f)/1024f;
            return ret;
        }
 
        private static int numOutputLines = 0;
 
        /// <summary>
        /// Event handler to redirect out CLI output
        /// </summary>
        /// <param name="sendingProcess"></param>
        /// <param name="outLine"></param>
        private static void exeOutputEventHandler(object sendingProcess,
                                                  DataReceivedEventArgs outLine)
        {
            if (!String.IsNullOrEmpty(outLine.Data))
            {
                numOutputLines++;
 
                Console.WriteLine("[" + numOutputLines.ToString("000") + "] - " + outLine.Data);
 
            }
        }
    }
}
 
 
 

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎