gpt4 book ai didi

c# - 在 C# 中使用非托管 FindFirstVolume 通过 .NET 枚举卷

转载 作者:行者123 更新时间:2023-11-30 17:20:48 24 4
gpt4 key购买 nike

我正在尝试枚举未安装驱动器字母的驱动器,以便我可以获得每个驱动器上的剩余空间。此应用程序必须与 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();
}

}

最佳答案

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

关于c# - 在 C# 中使用非托管 FindFirstVolume 通过 .NET 枚举卷,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3981277/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com