以编程方式格式化USB驱动器 [英] Formatting USB Drives programmatically

查看:67
本文介绍了以编程方式格式化USB驱动器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用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;
    } 

我不太确定有效.这是格式化USB驱动器的正确方法吗?如果没有,有人可以指出我正确的方向吗?

我尝试查看Win32_Volume类,但是,我还是不太了解它是如何工作的. 问题将建议使用CreateFile函数.我还查看了网站.

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

解决方案

也许我有另一种方法:

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

I am developing an application in C# so whereby, if the user confirms a messagebox to formatting a USB drive, selected from a combobox list, the drive will be formatted.

I haven't got an idea how to approach this, however - I have the following code:

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

I'm not really sure how this works. Is this the correct way to approach formatting USB Drives? If not, could someone point me in the right direction?

I have tried looking at the Win32_Volume class but, again, I don't really understand how it works. This question would suggest using the CreateFile function. I have also looked at this website.

Any tips of pushing me into the right direction, would be much appreciated.

解决方案

Well maybe I have another method:

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

First I wrote the code myself, now found a perfect method on http://www.metasharp.net/index.php/Format_a_Hard_Drive_in_Csharp

Answers to questions in comment:

Remove the /q if you don't want it to quick format

/x parameter forces the selected volume to dismount, if needed.

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

psi.CreateNoWindow = true;

Hides the terminal so your application looks smooth. My advice is showing it while debugging.

What you want to call is if the drive is F:/ for example:

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

这篇关于以编程方式格式化USB驱动器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆