开发者

Use unmanaged FindFirstVolume to enumerate volumes with .NET in C#

I am trying to enumerate drives that are mounted without a direve letter so I can obtain the remaining space on each of the drives. This application must work with Windows XP so the Win32_Volume class is not available.

When the following code is executed, a System.ExecutionEngineException is thrown.

using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections.Generic;

class Test : IDisposable
{
    public static void Main( string[] args )
    {
        try
        {
            GetVolumes();
        }
        catch (Exception e)
        {
            Console.WriteLine( e.ToString() );
        }
    }
    //HANDLE WINAPI FindFirstVolume(
    //  __out  LPTSTR lpszVolumeName,
    //  _开发者_如何学Python_in   DWORD cchBufferLength
    //);


    [DllImport( "kernel32.dll", EntryPoint = "FindFirstVolume", SetLastError = true, CallingConvention = CallingConvention.StdCall )]
    public static extern int FindFirstVolume(
      out StringBuilder lpszVolumeName,
      int cchBufferLength );


    [DllImport( "kernel32.dll", EntryPoint = "FindNextVolume", SetLastError = true, CallingConvention = CallingConvention.StdCall )]
    public static extern bool FindNextVolume(
      int hFindVolume,
      out StringBuilder lpszVolumeName,
      int cchBufferLength );

    public static List<string> GetVolumes()
    {

        const int N = 1024;
        StringBuilder cVolumeName = new StringBuilder( (int)N );
        List<string> ret = new List<string>();
        int volume_handle = FindFirstVolume( out cVolumeName, N );
        do
        {
            ret.Add( cVolumeName.ToString() );
            Console.WriteLine( cVolumeName.ToString() );
        } while (FindNextVolume( volume_handle, out cVolumeName, N ));
        return ret;
    }


    void IDisposable.Dispose()
    {
        throw new NotImplementedException();
    }

}


Remove out from before StringBuilder:

[DllImport( "kernel32.dll", EntryPoint = "FindFirstVolume", SetLastError = true, CallingConvention = CallingConvention.StdCall )]
public static extern int FindFirstVolume(
  StringBuilder lpszVolumeName,
  int cchBufferLength );


[DllImport( "kernel32.dll", EntryPoint = "FindNextVolume", SetLastError = true, CallingConvention = CallingConvention.StdCall )]
public static extern bool FindNextVolume(
  int hFindVolume,
  StringBuilder lpszVolumeName,
  int cchBufferLength );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜