Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Xml

Public Class Ficheros
    Public Shared Function FicheroAArrayBytes(ByVal RutaFichero As String) As Byte()
        Return IO.File.ReadAllBytes(RutaFichero)
        'FicheroAArrayBytes = Nothing
        'Try
        '    Dim fstmp As IO.FileStream, by() As Byte
        '    fstmp = IO.File.OpenRead(RutaFichero)
        '    ReDim by(fstmp.Length - 1)
        '    fstmp.Read(by, 0, fstmp.Length)
        '    fstmp.Close()
        '    FicheroAArrayBytes = by
        'Catch ex As Exception
        '    Throw New Exception(ex.Message, ex)
        'End Try
    End Function
    Public Shared Function FicheroAString(ByVal RutaFichero As String) As String
        Dim s As String
        Dim tr As IO.TextReader = New IO.StreamReader(RutaFichero)
        s = tr.ReadToEnd
        Return s
    End Function
    Public Shared Sub ByteArrayAFichero(Datos() As Byte, NombreFichero As String, Optional Sobreescribir As Boolean = False)
        If Not IO.Directory.Exists(IO.Path.GetDirectoryName(NombreFichero)) Then Utilidades.CreaEstructuraDirectorio(IO.Path.GetDirectoryName(NombreFichero))
        If IO.File.Exists(NombreFichero) And Sobreescribir Then IO.File.Delete(NombreFichero)
        Dim oFileStream As System.IO.FileStream
        oFileStream = New System.IO.FileStream(NombreFichero, System.IO.FileMode.Create)
        oFileStream.Write(Datos, 0, Datos.Length)
        oFileStream.Close()
    End Sub


    Public Shared Sub EliminaCaracteresInvalidosXML(FicheroOrigen As String, FicheroDestino As String)
        Dim reader As TextReader = New StreamReader(FicheroOrigen)
        Dim writer As TextWriter = New StreamWriter([FicheroDestino])
        Dim linea As String = reader.ReadLine
        Do Until linea Is Nothing
            writer.WriteLine(CleanInvalidXmlChars(linea))
            linea = reader.ReadLine
        Loop
        writer.WriteLine(CleanInvalidXmlChars(reader.ReadToEnd()))
        writer.Flush()
        reader.Close()
        writer.Close()
    End Sub

    Public Shared Sub EliminaCaracteresInvalidosXML(stOrigen As Stream, stDestino As Stream)
        Dim reader As TextReader = New StreamReader(stOrigen)
        Dim writer As TextWriter = New StreamWriter(stDestino)
        Dim linea As String = reader.ReadLine
        Do Until linea Is Nothing
            writer.WriteLine(CleanInvalidXmlChars(linea))
            linea = reader.ReadLine
        Loop
        writer.WriteLine(CleanInvalidXmlChars(reader.ReadToEnd()))
        writer.Flush()
        reader.Close()
        '  writer.Close()
        stDestino.Position = 0
    End Sub


    Public Shared Function CleanInvalidXmlChars(text As String) As String
        Dim re As String = "[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000-x10FFFF]"
        Return Regex.Replace(text, re, "")
    End Function
    Public Shared Function IndentaFicheroXML(ByVal FicheroOrigen As String, Codificacion As Text.Encoding) As String
        Dim result As String = ""
        Dim mStream As MemoryStream = New MemoryStream()
        Dim writer As XmlTextWriter = New XmlTextWriter(mStream, Codificacion)
        Dim document As XmlDocument = New XmlDocument()

        Try
            document.Load(FicheroOrigen)
            writer.Formatting = Formatting.Indented
            document.WriteContentTo(writer)
            writer.Flush()
            mStream.Flush()
            mStream.Position = 0
            Dim sReader As StreamReader = New StreamReader(mStream)
            Dim formattedXml As String = sReader.ReadToEnd()
            result = formattedXml
        Catch __unusedXmlException1__ As XmlException
        End Try

        mStream.Close()
        writer.Close()
        Return result
    End Function
    Public Shared Function IndentaXML(ByVal xml As String, Codificacion As Text.Encoding) As String
        Dim result As String = ""
        Dim mStream As MemoryStream = New MemoryStream()
        Dim writer As XmlTextWriter = New XmlTextWriter(mStream, Codificacion)
        Dim document As XmlDocument = New XmlDocument()

        Try
            document.LoadXml(xml)
            writer.Formatting = Formatting.Indented
            document.WriteContentTo(writer)
            writer.Flush()
            mStream.Flush()
            mStream.Position = 0
            Dim sReader As StreamReader = New StreamReader(mStream)
            Dim formattedXml As String = sReader.ReadToEnd()
            result = formattedXml
        Catch __unusedXmlException1__ As XmlException
        End Try

        mStream.Close()
        writer.Close()
        Return result
    End Function
    Public Shared Sub ObtieneFicherosRecursivo(ByVal Ruta As String, ByRef Ficheros() As String, OmitirErrores As Boolean)
        Dim sFicheros() As String = IO.Directory.GetFiles(Ruta)
        Dim iNumeroFicheros As Integer
        If Not IsNothing(Ficheros) Then iNumeroFicheros = Ficheros.Length
        ReDim Preserve Ficheros(sFicheros.Length - 1 + iNumeroFicheros)
        sFicheros.CopyTo(Ficheros, iNumeroFicheros)
        Dim sDirectorio, sDirectorios() As String
        Try
            sDirectorios = IO.Directory.GetDirectories(Ruta)
            For Each sDirectorio In sDirectorios
                Try
                    ObtieneFicherosRecursivo(sDirectorio, Ficheros, OmitirErrores)
                Catch ex As Exception
                    If Not OmitirErrores Then
                        Throw New Exception(ex.Message, ex)
                    End If
                End Try
            Next
        Catch ex As Exception
            If Not OmitirErrores Then
                Throw New Exception(ex.Message, ex)
            End If

        End Try
    End Sub
    Public Shared Sub EliminaDirectorio(Directorio As String, OmitirErrores As Boolean)
        Dim dirs = IO.Directory.GetDirectories(Directorio)
        For Each carpeta In dirs
            Try
                IO.Directory.Delete(carpeta, True)
            Catch ex As Exception
                If Not OmitirErrores Then
                    Throw New Exception(ex.Message, ex)
                End If
            End Try
        Next
        Dim sFicheros() As String = Nothing
        ObtieneFicherosRecursivo(Directorio, sFicheros, OmitirErrores)
        For Each f In sFicheros
            Try
                IO.File.Delete(f)
            Catch ex As Exception
                If Not OmitirErrores Then
                    Throw New Exception(ex.Message, ex)
                End If
            End Try
        Next
    End Sub
    Public Shared Sub EliminaFicherosTemporales()
        Dim tempfolder As String = Path.GetTempPath()
        EliminaDirectorio(tempfolder, True)
    End Sub
    Public Shared Function AcortarNombreArchivo(ByVal nombreArchivo As String, ByVal longitudMaximaIncluyendoExtension As Integer) As String
        ' Obtén la extensión del archivo
        Dim extension As String = System.IO.Path.GetExtension(nombreArchivo)

        ' Obtén el nombre base del archivo sin la extensión
        Dim nombreBase As String = System.IO.Path.GetFileNameWithoutExtension(nombreArchivo)

        ' Acorta el nombre base si es necesario
        If nombreArchivo.Length > longitudMaximaIncluyendoExtension Then
            nombreBase = nombreBase.Substring(0, longitudMaximaIncluyendoExtension - extension.Length)
        End If

        ' Combina el nombre base acortado con la extensión
        Return nombreBase & extension
    End Function

End Class
