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

 

 


Tema destacado: Security Series.XSS. [Cross Site Scripting]


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [C#] Comprobar contenido de textBox
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [C#] Comprobar contenido de textBox  (Leído 2,108 veces)
DeMoNcRaZy


Desconectado Desconectado

Mensajes: 420


$~*|_


Ver Perfil
[C#] Comprobar contenido de textBox
« en: 10 Septiembre 2015, 11:27 am »

Buenas,

Tengo un problema para verificar si un campo está textBox está en blanco.. si lo esta mandar una alerta y si no seguir con el procedimiento que es crear un directorio.

Código
  1. string path = @"C:\" + textBox1.Text;
  2.  
  3.            if(textBox1.Text == null)
  4.            {
  5.                MessageBox.Show("Debe asignar un nombre.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  6.            }
  7.            else
  8.            {
  9.                try
  10.                {
  11.                    // Comprobamos si existe el directorio
  12.                    if (Directory.Exists(path))
  13.                    {
  14.                        MessageBox.Show("La carpeta ya parece existir.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  15.                    }
  16.  
  17.                    // Creamos el directorio
  18.                    DirectoryInfo di = Directory.CreateDirectory(path);
  19.                    MessageBox.Show("Se ha creado una carpeta: " + Directory.GetCreationTime(path), "Exito", MessageBoxButtons.OK, MessageBoxIcon.Information);
  20.                }
  21.                catch (Exception)
  22.                {
  23.                    MessageBox.Show("Se ha producido un error.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  24.                }
  25.            }

Tengo esto, y cuando presiono el botón para crear.. me dice que el directorio ya existe, y luego otro mensaje de que se ha creado.. y no se ha creado nada.

Funciona bien hasta que le he añadido el if para comprobar que el textBox no estuviese en blanco.

¿Saben algo como podría arreglarlo?

Cualquier información adicional la agradecería.

Saludos.


En línea

Esta página web no está disponible - Google Chrome
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [C#] Comprobar contenido de textBox
« Respuesta #1 en: 10 Septiembre 2015, 15:11 pm »

1. No utilizar nombres de variables cómo path que puedan entrar en conflicto con nombres de namespaces, classes (System.IO.Path) u otros miembros built-in.

2. Referencia el texto del control TextBox1, ya que lo usas más de una vez.

3. También deberías comprobar, antes de intentar crear el directorio, si la ruta/nombre de directorio contiene caracteres ilegales, con la función System.IO.Path.GetInvalidFileNameChars o System.IO.Path.GetInvalidPathChars dependiendo de si es un nombre de carpeta o una ruta completa.

4. La variable di no la usas para nada, dale uso para evitar la siguiente llamada a Directory.GetCreationTime.

Un ejemplo:

Código
  1. Dim text As String = TextBox1.Text
  2. Dim dirPath As String = Path.Combine("C:\", text)
  3.  
  4. If String.IsNullOrEmpty(text) Then
  5.    MessageBox.Show("Debe asignar un nombre de directorio.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
  6.  
  7. ElseIf Path.GetInvalidFileNameChars.Any(Function(c) text.Contains(c)) Then
  8.    MessageBox.Show("El nombre de directorio contiene caracteres ilegales.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
  9.  
  10. ElseIf Directory.Exists(dirPath) Then
  11.    MessageBox.Show("El directorio ya existe.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
  12.  
  13. Else
  14.    Dim di As DirectoryInfo = Directory.CreateDirectory(dirPath)
  15.    MessageBox.Show(String.Format("Se ha creado una carpeta: {0}", di.CreationTime.ToString),
  16.                    "Éxito", MessageBoxButtons.OK, MessageBoxIcon.Information)
  17.  
  18. End If

Traducción online a C#:
Código
  1. string text = TextBox1.Text;
  2. string dirPath = Path.Combine("C:\\", text);
  3.  
  4. if (string.IsNullOrEmpty(text)) {
  5. MessageBox.Show("Debe asignar un nombre de directorio.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  6.  
  7. } else if (Path.GetInvalidFileNameChars.Any(c => text.Contains(c)) {
  8. MessageBox.Show("El nombre de directorio contiene caracteres ilegales.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  9.  
  10. } else if (Directory.Exists(dirPath)) {
  11. MessageBox.Show("El directorio ya existe.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  12.  
  13. } else {
  14. DirectoryInfo di = Directory.CreateDirectory(dirPath);
  15. MessageBox.Show(string.Format("Se ha creado una carpeta: {0}", di.CreationTime.ToString), "Éxito", MessageBoxButtons.OK, MessageBoxIcon.Information);
  16.  
  17. }
  18.  
  19. //=======================================================
  20. //Service provided by Telerik (www.telerik.com)
  21. //=======================================================



De todas formas para tratar temas de validación de datos introducidos en los campos de un control, lo apto graficamente hablando sería utilizar un proveedor de errores (ErrorProvider).



Ejemplo en VB.Net (el de la imagen GIF)
Código
  1. Imports System.IO
  2.  
  3. Public NotInheritable Class Form1 : Inherits Form
  4.  
  5.    Private ReadOnly Property DirectoryPath As String
  6.        Get
  7.            Return String.Format("C:\{0}", TextBox1.Text) ' o Path.Combine("C:\", TextBox1.Text)
  8.        End Get
  9.    End Property
  10.  
  11.    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) _
  12.    Handles TextBox1.TextChanged, TextBox1.Enter
  13.  
  14.        Dim tb As TextBox = DirectCast(sender, TextBox)
  15.  
  16.        If String.IsNullOrEmpty(tb.Text) Then
  17.            Me.ErrorProvider1.SetError(tb, "Debe asignar un nombre de directorio.")
  18.  
  19.        ElseIf Path.GetInvalidFileNameChars.Any(Function(c) tb.Text.Contains(c)) Then
  20.            Me.ErrorProvider1.SetError(tb, "El nombre de directorio contiene caracteres ilegales.")
  21.  
  22.        ElseIf Directory.Exists(Me.DirectoryPath) Then
  23.            Me.ErrorProvider1.SetError(tb, "El directorio ya existe.")
  24.  
  25.        Else
  26.            ' Eliminar error.
  27.            Me.ErrorProvider1.SetError(tb, String.Empty)
  28.  
  29.        End If
  30.  
  31.        Label1.Text = Me.ErrorProvider1.GetError(tb)
  32.        Button1.Enabled = String.IsNullOrEmpty(Label1.Text)
  33.  
  34.    End Sub
  35.  
  36.    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  37.  
  38.        Dim di As DirectoryInfo = Directory.CreateDirectory(Me.DirectoryPath)
  39.            MessageBox.Show(String.Format("Se ha creado una carpeta: {0}", di.CreationTime.ToString),
  40.                            "Éxito", MessageBoxButtons.OK, MessageBoxIcon.Information)
  41.  
  42.    End Sub
  43.  
  44. End Class

Traducción online a C#:
Código
  1. using Microsoft.VisualBasic;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Diagnostics;
  7. using System.IO;
  8.  
  9. public sealed class Form1 : Form
  10. {
  11.  
  12. private string DirectoryPath {
  13. // o Path.Combine("C:\", TextBox1.Text)
  14. get { return string.Format("C:\\{0}", TextBox1.Text); }
  15. }
  16.  
  17.  
  18. private void TextBox1_TextChanged(object sender, EventArgs e)
  19. {
  20. TextBox tb = (TextBox)sender;
  21.  
  22. if (string.IsNullOrEmpty(tb.Text)) {
  23. this.ErrorProvider1.SetError(tb, "Debe asignar un nombre de directorio.");
  24.  
  25. } else if (Path.GetInvalidFileNameChars.Any(c => tb.Text.Contains(c))) {
  26. this.ErrorProvider1.SetError(tb, "El nombre de directorio contiene caracteres ilegales.");
  27.  
  28. } else if (Directory.Exists(this.DirectoryPath)) {
  29. this.ErrorProvider1.SetError(tb, "El directorio ya existe.");
  30.  
  31. } else {
  32. // Eliminar error.
  33. this.ErrorProvider1.SetError(tb, string.Empty);
  34.  
  35. }
  36.  
  37. Label1.Text = this.ErrorProvider1.GetError(tb);
  38. Button1.Enabled = string.IsNullOrEmpty(Label1.Text);
  39.  
  40. }
  41.  
  42.  
  43. private void Button1_Click(object sender, EventArgs e)
  44. {
  45. DirectoryInfo di = Directory.CreateDirectory(this.DirectoryPath);
  46. MessageBox.Show(string.Format("Se ha creado una carpeta: {0}", di.CreationTime.ToString), "Éxito", MessageBoxButtons.OK, MessageBoxIcon.Information);
  47.  
  48. }
  49.  
  50. }
  51.  
  52. //=======================================================
  53. //Service provided by Telerik (www.telerik.com)
  54. //=======================================================


« Última modificación: 10 Septiembre 2015, 15:12 pm por Eleкtro » En línea

DeMoNcRaZy


Desconectado Desconectado

Mensajes: 420


$~*|_


Ver Perfil
Re: [C#] Comprobar contenido de textBox
« Respuesta #2 en: 10 Septiembre 2015, 15:33 pm »

Muchas gracias. Excelente explicación  ;)

Además me ha encantado la segunda opción de bloquear el botón, y además mandar errores sin un Message.Show.

Gracias de nuevo.

Saludos.
En línea

Esta página web no está disponible - Google Chrome
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Guardar contenido de TextBox
Programación Visual Basic
Gato Negro 2 3,710 Último mensaje 30 Enero 2008, 23:34 pm
por Gato Negro
Guardar el contenido de un textbox en la configuracion de la aplicacion. (vb.ne)
.NET (C#, VB.NET, ASP)
70N1 2 6,358 Último mensaje 17 Febrero 2010, 02:37 am
por elmaro
obtener contenido de un textbox
.NET (C#, VB.NET, ASP)
Roboto 3 5,137 Último mensaje 15 Marzo 2012, 18:35 pm
por dont'Exist
Comprobar última modificación disco duro y proteger su contenido
Seguridad
barradepan 0 2,225 Último mensaje 14 Mayo 2013, 20:36 pm
por barradepan
saber contenido textbox
Programación Visual Basic
siwsonu 2 2,243 Último mensaje 25 Agosto 2013, 18:57 pm
por siwsonu
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines