C#实现后台格式化U盘的功能

检测U盘:

1                 DriveInfo[] s = DriveInfo.GetDrives();
2                 var result = string.Empty;
3                 foreach (DriveInfo i in s)
4                 {
5                     if (i.DriveType == DriveType.Removable)  //这里就是可移动的设备了
6                     {
7                           break;
8                     }
9                 }

格式化磁盘:

        /// <summary>
        /// 格式化磁盘
        /// </summary>
        /// <param name="DiskName">盘符名称:C:、D:、E:、F:</param>
        /// <returns></returns>
        public bool FormatDisk(string DiskName)
        {
            ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
            processStartInfo.RedirectStandardInput = true;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.UseShellExecute = false;

            Process process = Process.Start(processStartInfo);

            if (process != null)
            {
                process.StandardInput.WriteLine($"FORMAT {DiskName} /y /FS:FAT32 /V:BMECG /Q");
                process.StandardInput.Close();

                string outputString = process.StandardOutput.ReadToEnd();
                if (outputString.Contains("已完成"))
                {
                    return true;
                }
            }
            return false;
        }

使用批处理 : 

FORMAT G: /Y /FS:NTFS /V:My_LABEL /Q

其中:

 G: is a drive letter for formating.  (需要格式化的磁盘)

/Y is used to force the format and bypass the confirmation (确认)

Do you really want to format the drive ?
Yes /No

 /FS is used to choose the file system either FAT32 Or NTFS  (设置格式)

/V is for labeling the drive after format  (格式化后的磁盘名)

/Q is used to perform quick format   (使用快速格式化)

原文地址:https://www.cnblogs.com/everydaygift/p/9555591.html