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
}
}

Link: http://www.metasharp.net/index.php/Format_a_Hard_Drive_in_Csharp

http://buffernow.com/format-drive-using-c/

Format a Hard Drive in Csharp C#格式化总结的更多相关文章

  1. Format a Hard Drive in Csharp

    Article Author(s): Audric Thevenet All Rights Reserved. Here's how to format hard drives, floppies, ...

  2. 使用date类和format类对系统当前时间进行格式化显示

    一:Date------------String 代码1:(代码二对显示出来的时间格式进行优化) package DateDemo; import java.text.SimpleDateFormat ...

  3. Python 3.x 格式化输出字符串 % & format 笔记

    Python 3.x 格式化输出字符串 % & format 笔记 python格式化字符串有%和{}两种 字符串格式控制符. 字符串输入数据格式类型(%格式操作符号) %%百分号标记 %c字 ...

  4. VBA 格式化字符串 - Format大全

    VBA 格式化字符串 VBA 的 Format 函数与工作表函数 TEXT 用法基本相同,但功能更加强大,许多格式只能用于VBA 的 Format 函数,而不能用于工作表函数 TEXT ,以下是本人归 ...

  5. 【C#】 格式化说明符 string.Format WriteLine

    定义 格式说明符的语法由3个字段组成:索引号.对齐说明符和格式字段.String.Format和WriteLine都遵守同样的格式化规则. 对齐说明符 对齐说明符表示了字段中字符的最小宽度.对齐说明符 ...

  6. C#中string.Format()和ToString()格式化方法

    C#数字格式化输出是我们在编程中经常需要处理的事情,那么这里向你介绍了一些C#数字格式化输出的例子,这样就会方便你来选择和比较,什么方式是比较适合自己项目的. int a = 12345678; C# ...

  7. 格式化日期时间字符串 Get-Date -Uformat , -format

    #将字符串格式化为时间格式 $dateTimeStr = '20141231T23:59:59' $format = 'yyyyMMddTHH:mm:ss' $formatProvider = [Gl ...

  8. java中实现与.net的format格式化字符串输出

    Java中的格式化字符串 System.out.println(MessageFormat.format("name={0}", "张三")); .net中的格 ...

  9. Python format 格式化函数

    str.format() 格式化字符串的函数 str.format(),它增强了字符串格式化的功能. 基本语法是通过 {} 和 : 来代替以前的 % format 函数可以接受不限个参数,位置可以不按 ...

随机推荐

  1. task-clph

    @UI方面 1 UILabel如果没有text内容,那么无论你怎么设置背景色都没用 UIButton就都可以用 2使用了新控件:UIStackView 使用步骤: //1创建 _horizontalS ...

  2. html5常用API之Full Screen

    所谓Full Screen API,就是全屏API,在html5中,该API允许开发者以编程方式将Web应用程序全屏运行,使Web应用程序更像本地应用程序.这款API十分简单有用,是html5初学者必 ...

  3. Android Toolbar样式定制详解

    前言 Marterial Design出来也有一段时间了,为了紧跟Google的设计规范,决定在项目中使用Toolbar.使用了一段时间之后,发现很多时候原始的Toolbar并不能满足项目的要求.为了 ...

  4. Eclipse 添加SVN

    第一种方法没试 第二种方法  可以使用 现在版本 最新为 1.10.x 1.下载最新的Eclipse,我的版本是3.7.2 indigo(Eclipse IDE for Java EE Develop ...

  5. 简单的css居中问题(日常记录)

    1.今天遇到了一个奇怪的问题:因为网页要适配大小分辨屏幕,需要把一张图片放到div中,我的初始思路是把图放在div中绝对对位给top50%left50%,但是不行,因为当网页调窄时图片就因为显得太大了 ...

  6. redis命令集合

    一.连接控制 QUIT 关闭连接 AUTH (仅限启用时)简单的密码验证 二.适合全体类型的命令 EXISTS key 判断一个键是否存在;存在返回 1;否则返回0;DEL key 删除某个key,或 ...

  7. 第一堂java web课

    一天的课程上完,虽然很累,但是因为自己的收获,所以我很开心. 第一节课老师带我们大家学习了HTML,学了很多标签,比如:html,head,body <html></html> ...

  8. 《javascript高级程序设计》第三章 Language Basics

    3.1 语法syntax 3.1.1 区分大小写case-sensitivity 3.1.2 标识符identifiers 3.1.3 注释comments 3.1.4 严格模式strict mode ...

  9. HTML5自学笔记[ 5 ]JSON的新方法

    eval和JSON.parse的区别:eval:可以解析任何字符串为js:parse:只能解析JSON形式的字符串变为js(更安全). json格式的字符串中的属性名必须加双引号“”. stringi ...

  10. Github/Eclipse管理Maven项目

    Eclipse和Git插件 (To-do: 直接从workspace导入也可以,弄明白这个repo管理的本质,查看sprigmvc是如何导入的) 最新版本的Eclipse都直接集成了Git插件 Ecl ...