Format Removable media with c# programming

最后都变了- 提交于 2021-02-05 04:54:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!