问题
I want to format (FAT32) removable drive with c# programming. In the internet I found a way, but the problem is that it opens the generic windows format program. But I want to do it with C# only and no built in windows support.
My method is:
// FAT32 Format Button click event
[DllImport("shell32.dll")]
static extern uint SHFormatDrive(IntPtr hwnd, uint drive, uint fmtID, uint options);
回答1:
You can use wmi, there is a method that allow this.
http://msdn.microsoft.com/en-us/library/aa390432%28v=VS.85%29.aspx
回答2:
I don't believe there is anything in C# that will generically do drive formatting, of any format. The method you have is likely the best way to do it on Windows.
If you want it truly generic you are still going to need some platform specific method of getting access to the hardware to do the job. C# is only going to provide you with standard I/O functionality.
You could look for third party libraries that are cross-platform if that is really what you are after. Chances are the solution you have may work on other platforms anyway (e.g. mono), although I don't know much about them.
回答3:
SHFormatDrive
is a high-level wrapper to an API called DeviceIoCtl
, which is used at the driver level to do things like format drives. You won't be able to bypass the dialog, since it's obviously designed as a shell method that incorporates a GUI.
I don't know what outside of actually p/invoke'ng DeviceIoCtl
you could use here. Mark Russinovich (of SysInternals fame) used to have a utility called "FormatX" that would do on NT4 what DeviceIOCtl does on later versions, but that seems to have been dicontinued, source and all. I think your other best bet is to create a separate command shell process that calls the format
utility with the correct parameters. Just open a console and type format /?
to get an idea. You can of course use System.Diagnostics.Process to do this with the command interpreter (with cmd.exe /c
).
回答4:
Works pretty good via WMI:
var query = String.Format("SELECT * FROM Win32_Volume WHERE Name = '{0}'", "E:\\\\");
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", query);
var queryCollection = from ManagementObject x in searcher.Get() select x;
var volume = queryCollection.FirstOrDefault();
var resultCode = volume.InvokeMethod("Format", new object[] { "FAT32", true, 4096, "Volume Name", false });
来源:https://stackoverflow.com/questions/3240377/format-removable-media-with-c-sharp-programming