Article Author(s): Audric Thevenet 
All Rights Reserved.


Here's how to format hard drives, floppies, usb drives, ... in C#.

Put the following code in a DriveManager.cs file in your project.

Add the following references :

System.Management (from the GAC)

You can now call this doing :

using Metasharp;
DriveManager.FormatDrive('R', "DriveName");

Have fun!

using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.Text; namespace Metasharp
{
public class DriveManager
{
#region SetLabel /// <summary>
/// set a drive label to the desired value
/// </summary>
/// <param name="driveLetter">drive letter. Example : 'A', 'B', 'C', 'D', ..., 'Z'.</param>
/// <param name="label">label for the drive</param>
/// <returns>true if success, false if failure</returns>
public static bool SetLabel(char driveLetter, string label = "")
{
#region args check if (!Char.IsLetter(driveLetter))
{
return false;
}
if (label == null)
{
label = "";
} #endregion
try
{
DriveInfo di = DriveInfo.GetDrives()
.Where(d => d.Name.StartsWith(driveLetter.ToString()))
.FirstOrDefault();
di.VolumeLabel = label;
return true;
}
catch (Exception)
{
return false;
}
} #endregion #region FormatDrive /// <summary>
/// Format a drive using the best available method
/// </summary>
/// <param name="driveLetter">drive letter. Example : 'A', 'B', 'C', 'D', ..., 'Z'.</param>
/// <param name="label">label for the drive</param>
/// <param name="fileSystem">file system. Possible values : "FAT", "FAT32", "EXFAT", "NTFS", "UDF".</param>
/// <param name="quickFormat">quick formatting?</param>
/// <param name="enableCompression">enable drive compression?</param>
/// <param name="clusterSize">cluster size (default=null for auto). Possible value depends on the file system : 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, ...</param>
/// <returns>true if success, false if failure</returns>
public static bool FormatDrive(char driveLetter, string label = "", string fileSystem = "NTFS", bool quickFormat = true, bool enableCompression = false, int? clusterSize = null)
{
return FormatDrive_CommandLine(driveLetter, label, fileSystem, quickFormat, enableCompression, clusterSize);
} #endregion #region FormatDrive_CommandLine /// <summary>
/// Format a drive using Format.com windows file
/// </summary>
/// <param name="driveLetter">drive letter. Example : 'A', 'B', 'C', 'D', ..., 'Z'.</param>
/// <param name="label">label for the drive</param>
/// <param name="fileSystem">file system. Possible values : "FAT", "FAT32", "EXFAT", "NTFS", "UDF".</param>
/// <param name="quickFormat">quick formatting?</param>
/// <param name="enableCompression">enable drive compression?</param>
/// <param name="clusterSize">cluster size (default=null for auto). Possible value depends on the file system : 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, ...</param>
/// <returns>true if success, false if failure</returns>
public static bool FormatDrive_CommandLine(char driveLetter, string label = "", string fileSystem = "NTFS", bool quickFormat = true, bool enableCompression = false, int? clusterSize = null)
{
#region args check if (!Char.IsLetter(driveLetter) ||
!IsFileSystemValid(fileSystem))
{
return false;
} #endregion
bool success = false;
string drive = driveLetter + ":";
try
{
var di = new DriveInfo(drive);
var psi = new ProcessStartInfo();
psi.FileName = "format.com";
psi.WorkingDirectory = Environment.SystemDirectory;
psi.Arguments = "/FS:" + fileSystem +
" /Y" +
" /V:" + label +
(quickFormat ? " /Q" : "") +
((fileSystem == "NTFS" && enableCompression) ? " /C" : "") +
(clusterSize.HasValue ? " /A:" + clusterSize.Value : "") +
" " + drive;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
var formatProcess = Process.Start(psi);
var swStandardInput = formatProcess.StandardInput;
swStandardInput.WriteLine();
formatProcess.WaitForExit();
success = true;
}
catch (Exception) { }
return success;
} #endregion #region FormatDrive_Shell32 #region interop // http://msdn.microsoft.com/en-us/library/windows/desktop/bb762169(v=vs.85).aspx
[DllImport("shell32.dll")]
private static extern uint SHFormatDrive(IntPtr hwnd, uint drive, SHFormatFlags fmtID, SHFormatOptions options); private enum SHFormatFlags : uint
{
SHFMT_ID_DEFAULT = 0xFFFF,
/// <summary>
/// A general error occured while formatting. This is not an indication that the drive cannot be formatted though.
/// </summary>
SHFMT_ERROR = 0xFFFFFFFF,
/// <summary>
/// The drive format was cancelled by user/OS.
/// </summary>
SHFMT_CANCEL = 0xFFFFFFFE,
/// <summary>
/// A serious error occured while formatting. The drive is unable to be formatted by the OS.
/// </summary>
SHFMT_NOFORMAT = 0xFFFFFFD
} [Flags]
private enum SHFormatOptions : uint
{
/// <summary>
/// Full formatting
/// </summary>
SHFMT_OPT_COMPLETE = 0x0,
/// <summary>
/// Quick Format
/// </summary>
SHFMT_OPT_FULL = 0x1,
/// <summary>
/// MS-DOS System Boot Disk
/// </summary>
SHFMT_OPT_SYSONLY = 0x2
} #endregion /// <summary>
/// Format a drive using Shell32.dll
/// </summary>
/// <param name="driveLetter">drive letter. Example : 'A', 'B', 'C', 'D', ..., 'Z'.</param>
/// <param name="label">label for the drive</param>
/// <param name="quickFormat">quick formatting?</param>
/// <returns>true if success, false if failure</returns>
[Obsolete("Unsupported by Microsoft nowadays. Prefer the FormatDrive() or FormatDrive_CommandLine() methods")]
public static bool FormatDrive_Shell32(char driveLetter, string label = "", bool quickFormat = true)
{
#region args check if (!Char.IsLetter(driveLetter))
{
return false;
} #endregion
bool success = false;
string drive = driveLetter + ":";
try
{
var di = new DriveInfo(drive);
var bytes = Encoding.ASCII.GetBytes(di.Name.ToCharArray());
uint driveNumber = Convert.ToUInt32(bytes[] - Encoding.ASCII.GetBytes(new[] { 'A' })[]);
var options = SHFormatOptions.SHFMT_OPT_COMPLETE;
if (quickFormat)
options = SHFormatOptions.SHFMT_OPT_FULL; uint returnCode = SHFormatDrive(IntPtr.Zero, driveNumber, SHFormatFlags.SHFMT_ID_DEFAULT, options);
if (returnCode == (uint)SHFormatFlags.SHFMT_ERROR)
throw new Exception("An error occurred during the format. This does not indicate that the drive is unformattable.");
else if (returnCode == (uint)SHFormatFlags.SHFMT_CANCEL)
throw new OperationCanceledException("The format was canceled.");
else if (returnCode == (uint)SHFormatFlags.SHFMT_NOFORMAT)
throw new IOException("The drive cannot be formatted."); SetLabel(driveLetter, label);
success = true;
}
catch (Exception) { }
return success;
} #endregion #region FormatDrive_Win32Api // http://msdn.microsoft.com/en-us/library/aa394515(VS.85).aspx /// <summary>
/// Format a drive using Win32 API
/// </summary>
/// <param name="driveLetter">drive letter. Example : 'A', 'B', 'C', 'D', ..., 'Z'.</param>
/// <param name="label">label for the drive</param>
/// <param name="fileSystem">file system. Possible values : "FAT", "FAT32", "EXFAT", "NTFS", "UDF".</param>
/// <param name="quickFormat">quick formatting?</param>
/// <param name="enableCompression">enable drive compression?</param>
/// <param name="clusterSize">cluster size. Possible value depends on the file system : 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, ...</param>
/// <returns>true if success, false if failure</returns>
[Obsolete("Might have troubles formatting ram drives. Prefer the FormatDrive() or FormatDrive_CommandLine() methods")]
public static bool FormatDrive_Win32Api(char driveLetter, string label = "", string fileSystem = "NTFS", bool quickFormat = true, bool enableCompression = false, int clusterSize = )
{
#region args check if (!Char.IsLetter(driveLetter) ||
!IsFileSystemValid(fileSystem))
{
return false;
} #endregion
bool success = false;
try
{
var moSearcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_Volume WHERE DriveLetter='" + driveLetter + ":'");
foreach (ManagementObject mo in moSearcher.Get())
{
mo.InvokeMethod("Format", new object[] { fileSystem, quickFormat, clusterSize, label, enableCompression });
success = true;
}
}
catch (Exception)
{
success = false;
}
return success;
} #endregion #region IsFileSystemValid /// <summary>
/// test if the provided filesystem value is valid
/// </summary>
/// <param name="fileSystem">file system. Possible values : "FAT", "FAT32", "EXFAT", "NTFS", "UDF".</param>
/// <returns>true if valid, false if invalid</returns>
public static bool IsFileSystemValid(string fileSystem)
{
#region args check if (fileSystem == null)
{
return false;
} #endregion
switch (fileSystem)
{
case "FAT":
case "FAT32":
case "EXFAT":
case "NTFS":
case "UDF":
return true;
default:
return false;
}
} #endregion
}
}

Format a Hard Drive in Csharp的更多相关文章

  1. Format a Hard Drive in Csharp C#格式化总结

    using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Management; ...

  2. WinSetupFromUSB – Install Windows XP from USB Flash Drive

    http://myeeeguides.wordpress.com/2008/11/15/winsetupfromusb-install-windows-xp-from-usb-flash-drive/ ...

  3. 在Virtual Box虚拟机中安装MS DOS!

    原文地址:https://mylinuxramblings.wordpress.com/2010/12/05/linux-mint-debian-edition-lmde-first-impressi ...

  4. MFC中GetPrivateProfileString相关函数

    项目中用到了这个函数,所以了解了一下,参考了一些博客: http://blog.sina.com.cn/s/blog_a599b5960101tsbk.html http://blog.csdn.ne ...

  5. VC中使用GetModuleFileName获取应用程序路径

      .\\与API函数GetModuleFileName获取应用程序目录有何不一样? 采用.\\也能获得应用程序目录,采用GetModuleFileName也能获得,二者有何不同? 一样!一个是相对路 ...

  6. errorlevel 续2

    -------siwuxie095             %ERRORLEVEL%值一览表:     ATTRIB.EXE (a) Target file/folder not found = ER ...

  7. GetModuleFileName和获取应用程序当前目录

    原文:http://www.cnblogs.com/xuemaxiongfeng/articles/2465544.html API函数GetModuleFileName():获得应用程序目录相对路径 ...

  8. Oz 创建Windows2008R2镜像

    此tdl和auto文件只可定义windows disk bus以ide模式启动,不支持virtio. <template> <name>Windows-gushiren< ...

  9. UEFI Bootable USB Flash Drive - Create in Windows(WIN7 WIN8)

    How to Create a Bootable UEFI USB Flash Drive for Installing Windows 7, Windows 8, or Windows 8.1 In ...

随机推荐

  1. UI:数据库练习、滤镜效果

    相机处理滤镜效果 滤镜主要使用在相机的美颜. #import "ViewController.h" #import "ImageUtil.h" #import ...

  2. eclipse+PyDev里面import win32api报错的问题解决

    windows下面eclipse+PyDev的开发环境,安装了pywin32,写import win32api时老提示错误,在idle里正常执行. 原来是安装python库时,python安装路径下面 ...

  3. Android Layout XML属性研究--android:layout_marginBottom (转载)

    转自:http://blog.csdn.net/yanfangjin/article/details/7393023 在如下的xml配置文件中,起初对于android:layout_marginBot ...

  4. Javascript中的回调函数和匿名函数的回调示例介绍

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  5. Codeforces - 474D - Flowers - 构造 - 简单dp

    https://codeforces.com/problemset/problem/474/D 这道题挺好的,思路是这样. 我们要找一个01串,其中0的段要被划分为若干个连续k的0. 我们设想一个长度 ...

  6. python int对象的方法

    1.求绝对值 >>> a = -10 >>> a.__abs__() 10 >>> abs(10) 10 2.加法 >>> a ...

  7. bzoj 5496: [2019省队联测]字符串问题【SAM+拓扑】

    有一个想法就是暴力建图,把每个A向有和他相连的B前缀的A,然后拓扑一下,这样的图是n^2的: 考虑优化建图,因为大部分数据结构都是处理后缀的,所以把串反过来,题目中要求的前缀B就变成了后缀B 建立SA ...

  8. python 合集set,交集,并集,差集,对称差集别搞混

    有集合 x与y x = {1,2,3,4,5}y = {4,5,6,7,8} x和y的交集为 {4,5} x和y的对称差集{1, 2, 3, 6, 7, 8} x和y的并集{1, 2, 3, 4, 5 ...

  9. 黑客攻防技术宝典web实战篇:Web 应用程序技术习题

    猫宁!!! 参考链接:http://www.ituring.com.cn/book/885 随书答案. 1. OPTIONS 方法有什么作用? OPTIONS 方法要求服务器报告可用于特定资源的 HT ...

  10. stylus基础教程,stylus实例教程,stylus语法总结

    stylus特点富于表现力.具有健壮性.功能丰富.动态编码不需要写CSS的冒号.分号.大括号和LESS.SASS功能类似,会这些的入手很快stylus特点安装使用stylus语法(一)选择器(二)变量 ...