|
9951
|
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. #Region " Make Dir Function " ' [ Make Dir Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' MsgBox(MakeDir("C:\Test")) Private Function Make_Dir(ByVal Path As String, Optional ByVal Attributes As System.IO.FileAttributes = IO.FileAttributes.Normal) If My.Computer.FileSystem.DirectoryExists(Path) Then Return Nothing ' Directory already exists Try My.Computer.FileSystem.CreateDirectory(Path) ' Create directory If Not Attributes = IO.FileAttributes.Normal Then My.Computer.FileSystem.GetDirectoryInfo(Path).Attributes = Attributes ' Apply Folder Attributes Return True ' Directory is created OK Catch ex As Exception Return False ' Can't create the directory maybe because user permissions ' Return ex.Message End Try End Function #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. #Region " Copy File Function " ' [ Copy File Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' MsgBox(Copy_File("C:\File.txt", "C:\Test\")) ' Standard copy ' MsgBox(Copy_File("C:\File.txt", "C:\Test\", True)) ' Create the directory if doesn't exists ' MsgBox(Copy_File("C:\File.txt", "C:\Test\", , True)) ' Replace any existing file ' MsgBox(Copy_File("C:\File.txt", "C:\Test\", , , IO.FileAttributes.Hidden + IO.FileAttributes.ReadOnly)) ' Apply new attributes Private Function Copy_File (ByVal File As String, ByVal Target_Path As String, _ Optional ByVal Force_Target_Path As Boolean = False, Optional ByVal Force_File_Replace As Boolean = False, _ Optional ByVal Attributes As System.IO.FileAttributes = IO.FileAttributes.Normal) Dim File_Information = My. Computer. FileSystem. GetFileInfo(File) ' Get Input File Information ' Directory If Not Force_Target_Path And Not My.Computer.FileSystem.DirectoryExists(Target_Path) Then Return False ' Target Directory don't exists ElseIf Force_Target_Path Then Try My.Computer.FileSystem.CreateDirectory(Target_Path) ' Create directory Catch ex As Exception 'Return False Return ex.Message ' Directory can't be created maybe beacuse user permissions End Try End If ' File Try My. Computer. FileSystem. CopyFile(File, Target_Path & "\" & File_Information. Name, Force_File_Replace ) ' Copies the file If Not Attributes = IO.FileAttributes.Normal Then My.Computer.FileSystem.GetFileInfo(Target_Path & "\" & File_Information.Name).Attributes = Attributes ' Apply File Attributes Return True ' File is copied OK Catch ex As Exception 'Return False Return ex.Message ' File can't be created maybe beacuse user permissions End Try End Function #End Region
|
|
|
9952
|
Programación / Scripting / Re: menu bath cambiar codigo
|
en: 15 Enero 2013, 03:48 am
|
Aquí tienes un menú, y sin usar SETLOCAL.  :: By Elektro H@cker Set "DefaultExt=bat doc cmd exe txt" :MENU CLS SET /A Count+=1 & REM Sumo un valor en el contador Call SET "EXT %%COUNT%%=%%@" & REM Creo la variable dinámica que contendrá cada extensión Call <Nul SET /P =[ %%COUNT%%] %%@ & REM Muestro las extensiones REM Si quieres la lista en horizontal en lugar de vertical elimina la línea del echo ) Choice /C AEN /m "[A]Agregar, [E] Eliminar, [N] Nada" :Agregar CLS Echo: [ Agregar extension ] | MORE SET /p "ADDEXT= AGREGA UNA EXTENSION >> " SET "ADDEXT= %ADDEXT:.=%" & REM Elimino cualquier punto SET "ADDEXT= %ADDEXT: =%" & REM Elimino cualquier espacio SET "DefaultExt= %DefaultExt% %ADDEXT%" & REM Añado la nueva extensión a la lista de extensiones :Eliminar CLS Echo: [ Eliminar extension ] | MORE Set "ChoiceDigits=" & REM Reseteo la variable Call Echo [ %%X] %%EXT%%X%% & REM Muestro las variables que creé en el menú Call Set "ChoiceDigits= %%ChoiceDigits%%%%X" & REM Seteo las opciones del comando CHOICE ) Choice /C %ChoiceDigits%N /M "[N] Ninguna" Call Set "DEL_EXT= %%EXT%ERRORLEVEL %%%" & REM Seteo la extensión elegida call SET "DefaultExt= %%DefaultExt:%DEL_EXT %=%%" & REM Elimino la extensión de la lista call SET "DefaultExt= %%DefaultExt: = %%" & REM Elimino dobles espacios si quedasen. :Copiar CLS Set "DefaultExt= %DefaultExt: = ,*.%" & REM Modifico los espacios de la variable para añadirlo los símbolos necesarios :: FOR /R "%userprofile%\Mis documentos\" %%a IN (*.%DefaultExt%) DO (copy /y "%%a" "E:\datossss\")
Saludos
|
|
|
9955
|
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 #Region " String To Case Function " ' [ String To Case Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Lower)) ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Upper)) ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Word)) ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Title)) ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Title, True)) Enum StringCase Lower Upper Title Word End Enum Public Function String_To_Case(ByVal Input_String As String, ByVal StringCase As StringCase, Optional ByVal Reverse As Boolean = False) As String If Not Input_String = Nothing And Not Input_String = "" Then Dim Output_String As String = Nothing Select Case StringCase Case StringCase.Lower : Output_String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToLower(Input_String) Case StringCase.Upper : Output_String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToUpper(Input_String) Case StringCase.Title : Output_String = Char.ToUpper(Input_String(0)) + StrConv(Input_String.Substring(1), VbStrConv.Lowercase) Case StringCase.Word : Output_String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Input_String) End Select If Reverse Then Return Microsoft.VisualBasic.StrReverse(Output_String) Else Return Output_String Else : Return False ' Any string to convert End If End Function #End Region
|
|
|
9956
|
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: ' MsgBox(Get_Directory_Size(New IO.DirectoryInfo("C:\_"), True)) Private Function Get_Directory_Size(Dir_Info As IO.DirectoryInfo, Include_Subfolders As Boolean) As Long Dim Dir_Total_Size As Long = Dir_Info. EnumerateFiles(). Sum(Function(file) file. Length) If Include_Subfolders Then Dir_Total_Size += Dir_Info.EnumerateDirectories().Sum(Function(dir) Get_Directory_Size(dir, True)) Return Dir_Total_Size 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 FunctionEDITO: Olviden lo que he dicho, con un TRY y listo 
|
|
|
9957
|
Programación / .NET (C#, VB.NET, ASP) / Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
|
en: 14 Enero 2013, 03:01 am
|
@ NovluckerQue grande, antes de nada debo decir que para mi tus críticas o sugerencias (O ataques personales si se da el caos xD) son más que bien recibidas, y segundo, gracias por colocarle chincheta al tema (Quien haya sido xD), a ver si la gente se anima a compartir funciones/snippets. Voy por partes:
1. Sincéramente yo no le daba nada de importancia a definir el tipo de retorno de una función, ¿Porque?, pues no sé, quizás séa porque como muchas funciones las he hecho yo pues sé perfectamente que tipo de valor devuelven y no debo fijarme en esos detalles que comentas, o simplemente no le he dado importancia sin razón alguna, pero me lo has hecho ver de una manera en la que no me habia fijado, y te aseguro que estoy editando los 124 snippets definiendo el tipo de retorno de cada uno xD. Lo malo de esto, es que si declaro el tipo en boolean (Por ejemplo), entonces ya no puedo retornar el mensaje de la excepción (Return ex.message), ¿O si?.
2. Con tu modificación que le has hecho a la función de los atributos me has dejado loco! Diréctamente no la entiendo... Attributes.Select(Function(a) DirectCast(a, Integer)).Sum() De ahí lo único que entiendo es que modificas el valor "a" a tipo entero (no se lo que significa esa "a"), lo de "Select", "Function", y "Sum, ni idea XD Bueno, el método "Sum" ya he visto que crea una sequencia parecida a esto: Lo que equivale a los valores para cambiar los atributos, vale, pero el proceso que haces para llegar a generar esa secuencia... ni idea  . Lo peor de todo es que no sé usar tu modificación de la función de atributos, es muy avanzada '¬¬ Así que mientras no me muestres un ejemplo de como usar tu función, la dejo así, que está mejor que la versión original y se asemeja al comando ATTRIB de la CMD, lo que me facilita un poco más su uso: #Region " Change File Attributes Function " ' [ Change File Attributes Function ] ' ' // By Elektro H@cker ' ' Examples : ' Change_File_Attributes("C:\File.txt", H + R) ' Change_File_Attributes("C:\File.txt", Hidden + Read_Only) Const Archive As Integer = 32, A As Integer = 32 Const Directory As Integer = 16, D As Integer = 16 Const Hidden As Integer = 2, H As Integer = 2 Const Normal As Integer = 0, N As Integer = 0 Const Read_Only As Integer = 1, R As Integer = 1 Const System As Integer = 4, S As Integer = 4 Const Volume As Integer = 8, V As Integer = 8 Private Function Change_File_Attributes (ByVal File As String, ByVal Attributes As System. IO. FileAttributes) As Boolean Try FileSystem. SetAttr(File, Attributes ) Return True ' File was modified OK Catch Return False ' File can't be modified maybe because User Permissions End Try Else Return Nothing ' File doesn't exist End If End Function #End Region
3. Tu modificación de la función de las capacidades de discos es inmejorable, Me doy cuenta que tengo que usar más las constantes y las enumeraciones si quiero perfeccionar y simplificar las cosas (Si te digo la verdad pensé que esa función no se podía simplificar más, hasta que he visto tu modificación xDDD, me kawen tó) Gracias por los consejos y un saludo
|
|
|
9958
|
Programación / .NET (C#, VB.NET, ASP) / Re: dudas visual basic 2012
|
en: 14 Enero 2013, 01:51 am
|
La verdad es que el las Metro apps son flipantes, que estilo!! . Para programar una Metro APP además tienes que programarla usando Windows 8, desde Windows 7 no podrás (Microsoft siempre haciendonos la vida "así de fácil"  ). Saludos!
|
|
|
9959
|
Programación / .NET (C#, VB.NET, ASP) / [SOLUCIONADO] Cual es la forma más simple de obtener el tamaño de una carpeta?
|
en: 14 Enero 2013, 01:45 am
|
Necesito obtener el tamaño de una carpeta. Como me gusta hacer las cosas perfectas (A pesar de lo poco que sé todavía de .NET) pues quiero saber si conocen alguna forma más simple (es decir, más rápida) que usar un directory.GetFiles... Me he fijado en que en el explorer cuando clickamos en las propiedades de una carpeta para ver el tamaño, pues parece que vaya contando los archivos y se vaya incrementando de tamaño, PERO!!... por otro lado, si hacemos lo mismo sobre un disco duro u otro dispositivo, el tamaño se muestra en un segundo, y además, con el Scripting.FileSystemObject es tán simple como esto: Dim folder As Scripting.FolderClass = fs.GetFolder(Environment.GetFolderPath(Environment.SpecialFolder.Personal)) MessageBox.Show(folder.Size) (Pero no forma parte de .NET) Así que tengo muchas dudas de si usar el método GetFiles es la única manera y la más rápida... PD: He buscado mucho en Google y solo veo Getfiles por todas partes. Gracias por leer.
|
|
|
9960
|
Programación / Programación General / Re: Duda_borrar_Linea_en_Fichero
|
en: 13 Enero 2013, 23:13 pm
|
(Sacado de Google) Dim file As New FileStream (data_path & "notes.txt", FileMode. Open) Dim text As String = Nothing Dim reader As New StreamReader (file) Dim writer As New StreamWriter (file) While Not reader.EndOfStream text = reader.ReadLine If text.Contains(value) Then text.Replace(value, "") writer.Write(text) End If End While
Usa un convertidor de código online VB.NET -> C#Aquí tienes otro ejemplo más simplificado: To remove item from text file, first move all text to a list and remove whichever item you want. Then write the text stored in the list into text file List<string> quotelist=File.ReadAllLines(filename).ToList(); string firstItem= quotelist[0]; quotelist.RemoveAt(0); File.WriteAllLines(filename, quotelist.ToArray()); return firstItem;
|
|
|
|
|
|
|