以编程方式格式化USB驱动器

时间:2015-10-14 08:33:31

标签: c# winforms format

我正在用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网站。

任何将我推向正确方向的提示都会非常感激。

2 个答案:

答案 0 :(得分:0)

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

    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);

答案 1 :(得分:0)

我也试过这个并且工作过:

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

也许会有所帮助。

相关问题