【问题标题】:Use unmanaged FindFirstVolume to enumerate volumes with .NET in C#使用非托管 FindFirstVolume 在 C# 中使用 .NET 枚举卷
【发布时间】:2010-10-20 18:52:51
【问题描述】:

我正在尝试枚举安装时没有驱动字母的驱动器,以便我可以获得每个驱动器上的剩余空间。此应用程序必须与 Windows XP 一起使用,因此 Win32_Volume 类不可用。

执行以下代码时,会抛出 System.ExecutionEngineException。

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,
    //  __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();
    }

}

【问题讨论】:

    标签: c# .net unmanaged winapi


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多