elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado:


  Mostrar Mensajes
Páginas: 1 ... 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 [978] 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 ... 1236
9771  Programación / .NET (C#, VB.NET, ASP) / Re: [APORTE] Snippets !! (Posteen aquí sus snippets) en: 15 Enero 2013, 07:33 am
He añadido, ordenado, y mejorado bastantes snippets del pack de snippets, el nuevo enlace está en el comentario principal.

 
Función para eliminar atributos de un archivo, preservando el resto de atributos.

Código
  1. #Region " File Remove Attribute Function "
  2.  
  3.    ' [ File Remove Attribute Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(File_Remove_Attribute("C:\Test.txt", FileAttribute.ReadOnly))
  8.    ' MsgBox(File_Remove_Attribute("C:\Test.txt", FileAttribute.ReadOnly + FileAttribute.Hidden))
  9.  
  10.    Public Function File_Remove_Attribute(ByVal File As String, ByVal Remove_Attribute As FileAttribute) As Boolean
  11.        Try
  12.            Dim FileAttributes As FileAttribute = IO.File.GetAttributes(File)
  13.            IO.File.SetAttributes(File, FileAttributes And Not Remove_Attribute)
  14.            Return True
  15.        Catch ex As Exception
  16.            Return False
  17.        End Try
  18.    End Function
  19.  
  20. #End Region


Función para añadir atributos a un archivo, preservando el resto de atributos.

Código
  1. #Region " File Add Attribute Function "
  2.  
  3.    ' [ File Add Attribute Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(File_Add_Attribute("C:\Test.txt", FileAttribute.ReadOnly))
  8.    ' MsgBox(File_Add_Attribute("C:\Test.txt", FileAttribute.ReadOnly + FileAttribute.Hidden))
  9.  
  10.    Public Function File_Add_Attribute(ByVal File As String, ByVal Add_Attribute As FileAttribute) As Boolean
  11.        Try
  12.            Dim FileAttributes As FileAttribute = IO.File.GetAttributes(File)
  13.            IO.File.SetAttributes(File, FileAttributes Or Add_Attribute)
  14.            Return True
  15.        Catch ex As Exception
  16.            Return False
  17.        End Try
  18.    End Function
  19.  
  20. #End Region

Función que comprueba si un archivo tiene un atributo

Código
  1. #Region " File Have Attribute Function "
  2.  
  3.    ' [ File Have Attribute Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(File_Have_Attribute("C:\Test.txt", FileAttribute.ReadOnly))
  8.    ' MsgBox(File_Have_Attribute("C:\Test.txt", FileAttribute.ReadOnly + FileAttribute.Hidden))
  9.  
  10.    Public Function File_Have_Attribute(ByVal File As String, ByVal CheckAttribute As FileAttribute) As Boolean
  11.        Try
  12.            Dim FileAttributes As FileAttribute = IO.File.GetAttributes(File)
  13.            If (FileAttributes And CheckAttribute) = CheckAttribute Then Return True Else Return False
  14.        Catch ex As Exception
  15.            Return Nothing
  16.        End Try
  17.  
  18.    End Function
  19.  
  20. #End Region
9772  Programación / .NET (C#, VB.NET, ASP) / Re: [APORTE] Snippets !! (Posteen aquí sus snippets) en: 15 Enero 2013, 07:11 am
Crea un acceso directo a una aplicación o a una página web, con muchas opciones.

Código
  1. #Region " Create ShortCut Function "
  2.  
  3.    ' [ Create ShortCut Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Create_ShortCut(ShortcutPath.MyDocuments, "My APP Shortcut.lnk", "C:\File.exe")
  10.    ' Create_ShortCut(ShortcutPath.Desktop, "My CMD Shortcut.lnk", "CMD.exe", "/C Echo Hello World & Pause")
  11.    ' Create_ShortCut(ShortcutPath.Favorites, "My INTERNET Shortcut.lnk", "http://www.Google.com", , "CTRL+SHIFT+S")
  12.    ' Create_ShortCut(ShortcutPath.Favorites, "My INTERNET Shortcut.lnk", "http://www.Google.com", , "CTRL+SHIFT+S", "Description of the shortcut")
  13.  
  14.    Enum ShortcutPath
  15.        AppData = Environment.SpecialFolder.ApplicationData
  16.        Desktop = Environment.SpecialFolder.Desktop
  17.        Favorites = Environment.SpecialFolder.Favorites
  18.        LocalAppData = Environment.SpecialFolder.LocalApplicationData
  19.        MyDocuments = Environment.SpecialFolder.MyDocuments
  20.        ProgramFiles = Environment.SpecialFolder.ProgramFiles
  21.        ProgramFilesx86 = Environment.SpecialFolder.ProgramFilesX86
  22.        StartMenu = Environment.SpecialFolder.StartMenu
  23.        System32 = Environment.SpecialFolder.System
  24.        SysWOW64 = Environment.SpecialFolder.SystemX86
  25.        UserProfile = Environment.SpecialFolder.UserProfile
  26.        Windows = Environment.SpecialFolder.Windows
  27.    End Enum
  28.  
  29.    Function Create_ShortCut(ByVal Shortcut_Path As ShortcutPath, _
  30.                            ByVal Shortcut_Name As String, _
  31.                            ByVal APP As String, _
  32.                            Optional ByVal APP_Arguments As String = Nothing, _
  33.                            Optional ByVal HotKey As String = Nothing, _
  34.                            Optional ByVal Icon As String = Nothing, _
  35.                            Optional ByVal Description As String = Nothing) As Boolean
  36.  
  37.        Dim Dir = New IO.DirectoryInfo(System.Environment.GetFolderPath(Shortcut_Path))
  38.        Dim WorkingDir As IO.FileInfo
  39.        If Not APP.Contains("/") Then WorkingDir = New IO.FileInfo(APP) Else WorkingDir = Nothing
  40.        Try
  41.            Dim WSHShell As Object = CreateObject("WScript.Shell")
  42.            Dim Shortcut As Object
  43.            Shortcut = WSHShell.CreateShortcut(Dir.FullName & "\" & Shortcut_Name)
  44.            Shortcut.TargetPath = APP
  45.            Shortcut.Arguments = APP_Arguments
  46.            Shortcut.WindowStyle = 2
  47.            Shortcut.Hotkey = HotKey
  48.            Shortcut.Description = Description
  49.            If Not APP.Contains("/") Then Shortcut.WorkingDirectory = WorkingDir.DirectoryName
  50.            If Icon IsNot Nothing Then Shortcut.IconLocation = Icon Else Shortcut.IconLocation = APP
  51.            Shortcut.Save()
  52.            Return True
  53.        Catch ex As Exception
  54.            Return False
  55.        End Try
  56.    End Function
  57.  
  58. #End Region
9773  Programación / Scripting / Re: Programa que simula la presión de teclas en: 15 Enero 2013, 05:52 am
Batch es .bat, ¿verdad?
Sí.
Como te digo en Batch no es posible enviar pulsaciones del teclado, a menos que mezcles VBS con Batch o uses aplicaciones externas (Lo cual significa compilar o unirlo de alguna manera por ejemplo con WinRAR),
Así que te puse el código en VisualBasicScript para no hacer un engorro de código usando Batch.

no sabría como generar el programa usando su código en VBS. De todos modos, muchas gracias.
Sigue las instrucciones de SegadorFelix, tán fácil como ponerle la extensión VBS al script.

PD: Y luego puedes ejecutar el VBS desde batch la CMD con el intérprete adecuado:
Código:
Ccript.exe "Archivo.vbs"
Código:
WScript.exe "Archivo.vbs"

Saludos
9774  Programación / Scripting / Re: Como evito que python muestre el CMD al ejecutar un script con pyQT4? en: 15 Enero 2013, 05:47 am
Guarda el archivo con extensión PYW

Saludos.
9775  Programación / .NET (C#, VB.NET, ASP) / Re: [APORTE] Snippets !! (Posteen aquí sus snippets) en: 15 Enero 2013, 05:05 am
Make Dir, para crear directorios con opción de añadir atributos.

Código
  1. #Region " Make Dir Function "
  2.  
  3.    ' [ Make Dir Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(MakeDir("C:\Test"))
  10.  
  11.    Private Function Make_Dir(ByVal Path As String, Optional ByVal Attributes As System.IO.FileAttributes = IO.FileAttributes.Normal)
  12.        If My.Computer.FileSystem.DirectoryExists(Path) Then Return Nothing ' Directory already exists
  13.        Try
  14.            My.Computer.FileSystem.CreateDirectory(Path) ' Create directory
  15.            If Not Attributes = IO.FileAttributes.Normal Then My.Computer.FileSystem.GetDirectoryInfo(Path).Attributes = Attributes ' Apply Folder Attributes
  16.            Return True ' Directory is created OK
  17.        Catch ex As Exception
  18.            Return False ' Can't create the directory maybe because user permissions
  19.            ' Return ex.Message
  20.        End Try
  21.    End Function
  22.  
  23. #End Region
Copy File , para copiar archivos, con opción de crear el directorio si no existe, opción de reemplazar archivos, y opcion de aplicar atributos al archivo.

Código
  1. #Region " Copy File Function "
  2.  
  3.    ' [ Copy File Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Copy_File("C:\File.txt", "C:\Test\")) ' Standard copy
  10.    ' MsgBox(Copy_File("C:\File.txt", "C:\Test\", True)) ' Create the directory if doesn't exists
  11.    ' MsgBox(Copy_File("C:\File.txt", "C:\Test\", , True)) ' Replace any existing file
  12.    ' MsgBox(Copy_File("C:\File.txt", "C:\Test\", , , IO.FileAttributes.Hidden + IO.FileAttributes.ReadOnly)) ' Apply new attributes
  13.  
  14.    Private Function Copy_File(ByVal File As String, ByVal Target_Path As String, _
  15.                               Optional ByVal Force_Target_Path As Boolean = False, Optional ByVal Force_File_Replace As Boolean = False, _
  16.                               Optional ByVal Attributes As System.IO.FileAttributes = IO.FileAttributes.Normal)
  17.  
  18.        Dim File_Information = My.Computer.FileSystem.GetFileInfo(File) ' Get Input File Information
  19.  
  20.        ' Directory
  21.        If Not Force_Target_Path And Not My.Computer.FileSystem.DirectoryExists(Target_Path) Then
  22.            Return False ' Target Directory don't exists
  23.        ElseIf Force_Target_Path Then
  24.            Try
  25.                My.Computer.FileSystem.CreateDirectory(Target_Path) ' Create directory
  26.            Catch ex As Exception
  27.                'Return False
  28.                Return ex.Message ' Directory can't be created maybe beacuse user permissions
  29.            End Try
  30.        End If
  31.  
  32.        ' File
  33.        Try
  34.            My.Computer.FileSystem.CopyFile(File, Target_Path & "\" & File_Information.Name, Force_File_Replace) ' Copies the file
  35.            If Not Attributes = IO.FileAttributes.Normal Then My.Computer.FileSystem.GetFileInfo(Target_Path & "\" & File_Information.Name).Attributes = Attributes ' Apply File Attributes
  36.            Return True ' File is copied OK
  37.        Catch ex As Exception
  38.            'Return False
  39.            Return ex.Message ' File can't be created maybe beacuse user permissions
  40.        End Try
  41.    End Function
  42.  
  43. #End Region
9776  Programación / Scripting / Re: menu bath cambiar codigo en: 15 Enero 2013, 03:48 am
Aquí tienes un menú, y sin usar SETLOCAL.

   

Código
  1. @Echo OFF
  2.  
  3.  
  4. :: By Elektro H@cker
  5.  
  6.  
  7. Set "DefaultExt=bat doc cmd exe txt"
  8.  
  9. :MENU
  10. CLS
  11. Set /A "Count=0"
  12. For %%@ in (%DefaultExt%) DO (
  13. SET /A Count+=1 & REM Sumo un valor en el contador
  14. Call SET "EXT%%COUNT%%=%%@" & REM Creo la variable dinámica que contendrá cada extensión
  15. Call <Nul SET /P =[%%COUNT%%] %%@ & REM Muestro las extensiones
  16. REM Si quieres la lista en horizontal en lugar de vertical elimina la línea del echo
  17. Echo+
  18. )
  19. Choice /C AEN /m "[A]Agregar, [E] Eliminar, [N] Nada"
  20. If %errorlevel% EQU 1 (CALL :Agregar)
  21. If %errorlevel% EQU 2 (CALL :Eliminar)
  22. If %errorlevel% EQU 3 (GOTO :Copiar)
  23. GOTO :MENU
  24.  
  25. :Agregar
  26. CLS
  27. Echo: [ Agregar extension ] | MORE
  28. SET /p "ADDEXT= AGREGA UNA EXTENSION >> "
  29. IF NOT DEFINED ADDEXT (GOTO :Agregar)
  30. SET "ADDEXT=%ADDEXT:.=%" & REM Elimino cualquier punto
  31. SET "ADDEXT=%ADDEXT: =%" & REM Elimino cualquier espacio
  32. SET "DefaultExt=%DefaultExt% %ADDEXT%" & REM Añado la nueva extensión a la lista de extensiones
  33. GOTO :EOF
  34.  
  35. :Eliminar
  36. CLS
  37. Echo: [ Eliminar extension ] | MORE
  38. Set "ChoiceDigits=" & REM Reseteo la variable
  39. For /L %%X in (1,1,%COUNT%) DO (
  40. Call Echo [%%X] %%EXT%%X%% & REM Muestro las variables que creé en el menú
  41. Call Set "ChoiceDigits=%%ChoiceDigits%%%%X" & REM Seteo las opciones del comando CHOICE
  42. )
  43. Choice /C %ChoiceDigits%N /M "[N] Ninguna"
  44. Call Set "DEL_EXT=%%EXT%ERRORLEVEL%%%" & REM Seteo la extensión elegida
  45. call SET "DefaultExt=%%DefaultExt:%DEL_EXT%=%%" & REM Elimino la extensión de la lista
  46. call SET "DefaultExt=%%DefaultExt:  = %%" & REM Elimino dobles espacios si quedasen.
  47. GOTO:EOF
  48.  
  49. :Copiar
  50. CLS
  51. Set "DefaultExt=%DefaultExt: = ,*.%" & REM Modifico los espacios de la variable para añadirlo los símbolos necesarios
  52. FOR %%a IN (*.%DefaultExt%) DO (echo "%%a")
  53. :: FOR /R "%userprofile%\Mis documentos\" %%a IN (*.%DefaultExt%) DO (copy /y "%%a" "E:\datossss\")
  54.  
  55. Pause&Exit

Saludos
9777  Programación / Scripting / Re: saber el tamano de un archivo en batch? en: 15 Enero 2013, 02:18 am
Código
  1. @Echo OFF
  2.  
  3. :chck_size
  4. if "%~z0" EQU "%VariableSize%" () ELSE ()
  5.  
  6. Pause&Exit

Saludos
9778  Programación / Programación General / Re: Tiempo qu en la universidad tarda aprender C# o si te lo enseñan intensivo bien en: 14 Enero 2013, 12:22 pm
Esperas que alguien te calcule la fecha y hora exacta basándose en un coeficiente intelectual :rolleyes:

Lo que está claro es que si no lo intentas y dejas de preguntar jamás lo aprenderás.

Saludos !
9779  Programación / .NET (C#, VB.NET, ASP) / Re: [APORTE] Snippets !! (Posteen aquí sus snippets) en: 14 Enero 2013, 08:09 am
Para convertir un string a lower,upper,wordcase o titlecase, con opción de invertir el string

Código
  1. #Region " String To Case Function "
  2.  
  3.    ' [ String To Case Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Lower))
  10.    ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Upper))
  11.    ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Word))
  12.    ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Title))
  13.    ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Title, True))
  14.  
  15.    Enum StringCase
  16.        Lower
  17.        Upper
  18.        Title
  19.        Word
  20.    End Enum
  21.  
  22.    Public Function String_To_Case(ByVal Input_String As String, ByVal StringCase As StringCase, Optional ByVal Reverse As Boolean = False) As String
  23.        If Not Input_String = Nothing And Not Input_String = "" Then
  24.            Dim Output_String As String = Nothing
  25.            Select Case StringCase
  26.                Case StringCase.Lower : Output_String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToLower(Input_String)
  27.                Case StringCase.Upper : Output_String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToUpper(Input_String)
  28.                Case StringCase.Title : Output_String = Char.ToUpper(Input_String(0)) + StrConv(Input_String.Substring(1), VbStrConv.Lowercase)
  29.                Case StringCase.Word : Output_String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Input_String)
  30.            End Select
  31.            If Reverse Then Return Microsoft.VisualBasic.StrReverse(Output_String) Else Return Output_String
  32.        Else : Return False ' Any string to convert
  33.        End If
  34.    End Function
  35.  
  36. #End Region
9780  Programación / .NET (C#, VB.NET, ASP) / Re: Cual es la forma más simple de obtener el tamaño de una carpeta? en: 14 Enero 2013, 04:12 am
Advertencia - mientras estabas escribiendo, una nueva respuesta fue publicada. Probablemente desees revisar tu mensaje.

Por "rápido" me refiero al performance, sí, a la que gaste menos recursos, menos tiempo, y la que no deba leer todos los archivos para saber el tamaño total (Si es que hubiera alguna que no lo hiciera, que parece que no).

Es una m**rda lo que comenta Novlucker porque ya lo he sufrido más de una vez, pero windows si que obtiene el tamaño de las carpetas que contienen archivos sin acceso, entonces alguna forma habrá, ¿No?

He reducido el code que me ha enseñado Seba, a esto:

Código
  1.    ' MsgBox(Get_Directory_Size(New IO.DirectoryInfo("C:\_"), True))
  2.  
  3.    Private Function Get_Directory_Size(Dir_Info As IO.DirectoryInfo, Include_Subfolders As Boolean) As Long
  4.        Dim Dir_Total_Size As Long = Dir_Info.EnumerateFiles().Sum(Function(file) file.Length)
  5.        If Include_Subfolders Then Dir_Total_Size += Dir_Info.EnumerateDirectories().Sum(Function(dir) Get_Directory_Size(dir, True))
  6.        Return Dir_Total_Size
  7.    End Function

El tema es... que no sé usar los identificadores de acceso, ya lo intenté hace unos días...

¿Como hago esto?:

Private Function Get_Directory_Size(Directory As IO.DirectoryInfo, Include_Subfolders As Boolean) As Long
        Dim Dir_Security As System.Security.AccessControl.DirectorySecurity = Directory.GetAccessControl()
        If Dir_Security = "SIN ACCESO a alguno de los archivos" Then
            Return Nothing
            ' bueno aquí tengo un lío de momento, quiero que salte el archivo y siga con el siguiente claro
        Else
            Dim Dir_Total_Size As Long = Directory.EnumerateFiles().Sum(Function(file) file.Length)
            If Include_Subfolders Then Dir_Total_Size += Directory.EnumerateDirectories().Sum(Function(dir) Get_Directory_Size(dir, True))
            Return Dir_Total_Size
        End If
    End Function


EDITO: Olviden lo que he dicho, con un TRY y listo  :xD
Páginas: 1 ... 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 [978] 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines