【问题标题】:Formatting USB Drives programmatically以编程方式格式化 USB 驱动器
【发布时间】:2020-09-02 13:01:40
【问题描述】:

我正在用 C# 开发一个应用程序,因此,如果用户确认从组合框列表中选择的用于格式化 USB 驱动器的消息框,驱动器将被格式化。

但是,我不知道如何处理这个问题 - 我有以下代码:

 public static bool FormatDrive(string driveLetter,
    string fileSystem = "FAT", bool quickFormat = false,
    int clusterSize = 4096, string label = "", bool enableCompression = false)
    {
        if (driveLetter.Length != 2 || driveLetter[1] != ':' || !char.IsLetter(driveLetter[0]))
            return false;

        //query and format given drive         
        ManagementObjectSearcher searcher = new ManagementObjectSearcher
         (@"select * from Win32_Volume WHERE DriveLetter = '" + driveLetter + "'");
        foreach (ManagementObject vi in searcher.Get())
        {
            vi.InvokeMethod("Format", new object[] { fileSystem, quickFormat, clusterSize, label, enableCompression });
        }

        return true;
    } 

我不太确定this 的工作原理。这是处理格式化 USB 驱动器的正确方法吗?如果没有,有人能指出我正确的方向吗?

我曾尝试查看 Win32_Volume 类,但我还是不太明白它是如何工作的。 This 问题建议使用 CreateFile 函数。我还查看了this 网站。

任何将我推向正确方向的提示,将不胜感激。

【问题讨论】:

  • 你真的需要完全格式化吗?还是您的目标只是删除其中的所有内容?
  • @CallumBradbury 需要完全格式化。但不能作为 QuickFormat 运行,因此将其设置为 false
  • Format a Drive from C#的可能重复
  • @user2754599 我也看过了。但这并不容易理解。至少,在我看来。
  • 只是好奇,为什么您希望使用自定义 C# 程序完全格式化它?已经有可用的格式化工具。

标签: c# winforms format


【解决方案1】:

好吧,也许我有另一种方法:

    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.CreateNoWindow         = true; //if you want to hide the window
            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;
    }

一开始我自己写了代码,现在在http://www.metasharp.net/index.php/Format_a_Hard_Drive_in_Csharp找到了一个完美的方法

评论中问题的答案:

如果您不想快速格式化,请删除 /q

/x 参数根据需要强制卸载选定的卷。

来源:http://ccm.net/faq/9524-windows-how-to-format-a-usb-key-from-the-command-prompt

psi.CreateNoWindow = true;

隐藏终端,使您的应用程序看起来流畅。我的建议是在调试时显示它。

你要调用的是驱动器是否为 F:/ 例如:

FormatDrive_CommandLine('F', "formattedDrive", "FAT32", false, false);

【讨论】:

  • /x 有什么作用?另外,您在哪里有driveLetter,我可以用combobox1.SelectedItem.ToString() 替换它吗?另外,这是否会保留所有设置,即 I.E、文件系统和集群大小?
  • 我添加了关于 toString 的解释:因为驱动器在 Windows 中总是有 1 个字符作为标识符,我建议使用 char 而不是 String,但当然你可以使用 String。
  • 谢谢。我添加了一个测试以确保 driveLetter 不是 C。
  • 它有效 :) 只需将 "exFAT" 更改为 "EXFAT" 即可获得正确的语法。谢谢!
  • 你会认为exFAT 是正确的语法,但唉,EXFAT
【解决方案2】:

我也试过这个并且成功了:

public bool FormatUSB(string driveLetter, string fileSystem = "FAT32", bool quickFormat = true,
                                   int clusterSize = 4096, string label = "USB_0000", bool enableCompression = false)
    {
        //add logic to format Usb drive
        //verify conditions for the letter format: driveLetter[0] must be letter. driveLetter[1] must be ":" and all the characters mustn't be more than 2
        if (driveLetter.Length != 2 || driveLetter[1] != ':' || !char.IsLetter(driveLetter[0]))
            return false;

        //query and format given drive 
        //best option is to use ManagementObjectSearcher

        var files = Directory.GetFiles(driveLetter);
        var directories = Directory.GetDirectories(driveLetter);

        foreach (var item in files)
        {
            try
            {
                File.Delete(item);
            }
            catch (UnauthorizedAccessException) { }
            catch (IOException) { }
        }

        foreach (var item in directories)
        {
            try
            {
                Directory.Delete(item);
            }
            catch (UnauthorizedAccessException) { }
            catch (IOException) { }
        }

        ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"select * from Win32_Volume WHERE DriveLetter = '" + driveLetter + "'");
        foreach (ManagementObject vi in searcher.Get())
        {
            try
            {
                var completed = false;
                var watcher = new ManagementOperationObserver();

                watcher.Completed += (sender, args) =>
                {
                    Console.WriteLine("USB format completed " + args.Status);
                    completed = true;
                };
                watcher.Progress += (sender, args) =>
                {
                    Console.WriteLine("USB format in progress " + args.Current);
                };

                vi.InvokeMethod(watcher, "Format", new object[] { fileSystem, quickFormat, clusterSize, label, enableCompression });

                while (!completed) { System.Threading.Thread.Sleep(1000); }


            }
            catch
            {

            }
        }
        return true;
    }
    #endregion

也许会有所帮助。

【讨论】:

  • 问题:这是否也改变了驱动器的格式?例如如果驱动器在格式化之前不是 FAT32,那么文件系统在使用此代码格式化之后是否会是 FAT32?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-18
  • 2014-09-07
  • 2013-12-31
  • 2017-07-18
  • 2017-06-24
  • 2021-04-12
相关资源
最近更新 更多