UNC space in VB. Net

He visto muchos puestos aquí (y en otros lugares) con una solución al problema de encontrar el espacio libre disponible en un camino de la UNC, pero todos ellos implican usar GetDiskFreeSpaceEx que sólo parece estar disponible en C.

Lo he incluido en un código de prueba y conseguir:

Error   BC30451 'GetDiskFreeSpaceEx' is not declared. It may be inaccessible due to its protection level.   

El IDE ofrece soluciones para crear un método o una propiedad.

Intentando esto en un programa de consolas...

¿Cuál es el equivalente VB de esto?

Pregunta hecha hace 3 años, 4 meses, 27 días - Por coderchampion


3 Respuestas:

  • Cuando trabajo con P/Invoke, generalmente escribo un clase con el nombre del método y no sólo el método se declara y Pruebe para exponer la funcionalidad en una moda .NET en lugar de estilo C++ de bajo nivel.

    por ejemplo en la descripción del método GetDiskFreeSpaceEx función se menciona que, en caso de que el camino proporcionado sea un UNC-path, el retroceso es obligatorio!

    • Estilo C+++: Escríbalo en la descripción, si el que llama no lo proporciona de esa manera, se culpan a sí mismos, RTFM.
    • . Estilo NET: Lo ajustamos para el llamador, no tienen que preocuparse por esos detalles de la implementación.

    También proporcionaría 3 métodos diferentes para cada información disponible (incluí un cuarto para el espacio utilizado), y uno común para obtener más de un valor a la vez.

    Aquí cómo podría verse:

    Imports System
    Imports System.ComponentModel
    Imports System.IO
    Imports System.Runtime.InteropServices
    
    Namespace PInvoke.Kernel32
    
        Public Class GetDiskFreeSpaceEx
    
            ''' 
            ''' Retrieves the number of bytes currently available to the caller. This takes into account any quotas etc. that may
            ''' exist on the folder resp. file share.
            ''' 
            ''' The name of the path to retrieve the for me available bytes from.
            ''' The maximum number of bytes that are currently available for me to use.
            Public Shared Function GetAvailableBytesToCaller(folderName As String) As UInt64
                Dim result As SizeInfo = Invoke(folderName)
                Return result.BytesAvailableToCaller
            End Function
    
            ''' 
            ''' Retrieves the number of bytes currently available on the according volume. This may be more than I can use,
            ''' see  for a method that respects quotas etc.
            ''' 
            ''' The name of the path to retrieve the (in general) available bytes from.
            ''' The maximum number of bytes that are available for all users together.
            Public Shared Function GetAvailableBytesInTotal(folderName As String) As UInt64
                Dim result As SizeInfo = Invoke(folderName)
                Return result.BytesAvailableInTotal
            End Function
    
            ''' 
            ''' Retrieves the number of bytes currently used on the according volume. This value corresponds to 
            '''  - .
            ''' 
            ''' The name of the path to retrieve the used bytes from.
            ''' The number of bytes that are already used by all users together.
            Public Shared Function GetUsedBytesInTotal(folderName As String) As UInt64
                Dim result As SizeInfo = Invoke(folderName)
                Return result.BytesUsedInTotal
            End Function
    
            ''' 
            ''' Retrieves the size in bytes of the according volume (the total of already used and available space).
            ''' 
            ''' The name of the path to retrieve the (in general) available bytes from.
            ''' The maximum number of bytes that are available for all users together.
            Public Shared Function GetBytesInTotal(folderName As String) As UInt64
                Dim result As SizeInfo = Invoke(folderName)
                Return result.TotalNumberOfBytes
            End Function
    
            ''' 
            ''' Retrieves a  object containing the information about how many bytes are available at
            ''' the given path in general or for the current user account, how much is the total and how much is already
            ''' used.
            ''' 
            ''' The name of the path from which to retrieve the size info.
            ''' The according size info object.
            Public Shared Function Invoke(folderName As String) As SizeInfo
                'Check argument
                If (String.IsNullOrWhiteSpace(folderName)) Then
                    Throw New ArgumentNullException(NameOf(folderName), "The folder's name must not be null, empty or white-space!")
                End If
                'Expand environment variables
                Try
                    folderName = Environment.ExpandEnvironmentVariables(folderName)
                Catch ex As Exception
                    Throw New ArgumentException($"Unable to expand possible environment variables of folder '{folderName}'! See inner exception for details...", ex)
                End Try
                'Get full path
                Try
                    folderName = Path.GetFullPath(folderName)
                Catch ex As Exception
                    Throw New ArgumentException($"Unable to retrieve absolute path of folder '{folderName}'! See inner exception for details...", ex)
                End Try
                'Append final back-slash (which is mandatory for UNC paths)
                folderName = folderName.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)
                If (Not folderName.EndsWith(Path.DirectorySeparatorChar)) Then
                    folderName &= Path.DirectorySeparatorChar
                End If
                'Invoke method
                Dim bytesAvailableToCaller As UInt64
                Dim bytesInTotal As UInt64
                Dim bytesAvailableInGeneral As UInt64
                Dim success As Boolean = Invoke(folderName, bytesAvailableToCaller, bytesInTotal, bytesAvailableInGeneral)
                If (Not success) Then Throw New Win32Exception()
                'Return result
                Return New SizeInfo(bytesAvailableToCaller, bytesInTotal, bytesAvailableInGeneral)
            End Function
    
            'Private Methods
    
            
            Private Shared Function Invoke(folderName As String, ByRef bytesAvailableToCaller As UInt64, ByRef bytesInTotal As UInt64, ByRef bytesAvailableInGeneral As UInt64) As  Boolean
            End Function
    
    
            '************************************************************************************************************************
            ' Inner Class "SizeInfo"
            '************************************************************************************************************************
    
            Public Class SizeInfo
    
                Public Sub New(freeBytesAvailableToCaller As UInt64, totalNumberOfBytes As UInt64, freeBytesAvailableInTotal As UInt64)
                    Me.BytesAvailableToCaller = freeBytesAvailableToCaller
                    Me.BytesAvailableInTotal = freeBytesAvailableInTotal
                    Me.TotalNumberOfBytes = totalNumberOfBytes
                End Sub
    
                Public ReadOnly Property BytesAvailableToCaller As UInt64
    
                Public ReadOnly Property BytesAvailableInTotal As UInt64
    
                Public ReadOnly Property BytesUsedInTotal As UInt64
                    Get
                        Dim total As UInt64 = TotalNumberOfBytes
                        Dim available As UInt64 = BytesAvailableInTotal
                        If (total <= available) Then Return 0
                        Return total - available
                    End Get
                End Property
    
                Public ReadOnly Property TotalNumberOfBytes As UInt64
    
            End Class
    
        End Class
    
    End Namespace
    

    Respondida el Dec 18, 2020 a las 13:41 - por compilerczar

    Votos positivos: 0 | Votos negativos: 0

  • En Visual Basic .NET, puedes utilizar la función GetDiskFreeSpace de la clase DriveInfo para obtener la información sobre el espacio libre en un camino de UNC (Universal Naming Convention). Aquí te dejo un ejemplo de cómo lo puedes hacer:

    vb
    Imports System.IO
    
    Module Module1
        Sub Main()
            Dim drivePath As String = "\\servidor\carpeta" ' Ruta del camino de UNC
    
            Dim driveInfo As New DriveInfo(drivePath)
    
            Dim freeSpace As Long = driveInfo.AvailableFreeSpace
    
            Console.WriteLine("Espacio libre en el camino UNC: " & freeSpace & " bytes")
        End Sub
    End Module
    

    Con el ejemplo anterior, puedes obtener la cantidad de espacio libre disponible en el camino de UNC especificado. Espero que esta solución sea útil para ti. Si tienes alguna otra pregunta, ¡no dudes en decírmelo!

    Respondida el Dec 19, 2020 a las 13:42 - por Gpt

    Votos positivos: 0 | Votos negativos: 0

  • El equivalente de VB.NET para la función GetDiskFreeSpaceEx de C++ es GetDiskFreeSpaceExW. Aquí tienes un ejemplo de cómo utilizarla:

    vb.net
    Imports System.Runtime.InteropServices
    
    Module Module1
    
        
        Private Shared Function GetDiskFreeSpaceExW(ByVal lpDirectoryName As String, ByRef lpFreeBytesAvailableToCaller As ULongPtr, ByRef lpTotalNumberOfBytes As ULongPtr, ByRef lpTotalNumberOfFreeBytes As ULongPtr) As Integer
        End Function
    
        Sub Main()
            Dim directoryName As String = "\\server\share"
            Dim freeBytesAvailableToCaller As ULongPtr
            Dim totalNumberOfBytes As ULongPtr
            Dim totalNumberOfFreeBytes As ULongPtr
    
            If GetDiskFreeSpaceExW(directoryName, freeBytesAvailableToCaller, totalNumberOfBytes, totalNumberOfFreeBytes) = 0 Then
                Console.WriteLine("Error: " & Marshal.GetLastWin32Error())
            Else
                Console.WriteLine("Bytes libres disponibles para el llamador: " & freeBytesAvailableToCaller.ToInt64())
                Console.WriteLine("Número total de bytes: " & totalNumberOfBytes.ToInt64())
                Console.WriteLine("Número total de bytes libres: " & totalNumberOfFreeBytes.ToInt64())
            End If
        End Sub
    
    End Module
    

    Nota:

    El tipo de datos ULongPtr es un alias de UInt64 en VB.NET. La función GetDiskFreeSpaceExW espera un puntero a un número entero sin signo de 64 bits para cada uno de sus parámetros de salida. En VB.NET, esto se implementa utilizando el tipo de datos ULongPtr. * Debes asegurarte de que la variable directoryName contiene la ruta UNC completa, incluyendo las barras invertidas iniciales.

    Respondida el Dec 19, 2020 a las 13:47 - por Gemini

    Votos positivos: 0 | Votos negativos: 0