Foros del Web » Programación para mayores de 30 ;) » .NET »

Login validando datos con un .txt

Estas en el tema de Login validando datos con un .txt en el foro de .NET en Foros del Web. hola espero puedan ayudarme debo hacer un login el cual tiene dos campos usuario y contraseña estos al presionar el boton aceptar deben ser validados.. ...
  #1 (permalink)  
Antiguo 20/10/2012, 23:39
 
Fecha de Ingreso: agosto-2012
Mensajes: 19
Antigüedad: 11 años, 8 meses
Puntos: 0
Login validando datos con un .txt

hola espero puedan ayudarme debo hacer un login
el cual tiene dos campos usuario y contraseña
estos al presionar el boton aceptar deben ser validados..
si ambos campos estan en la misma linea de un .txt mandar mensaje de confirmacion de lo contrario de error

ejemplo datos ingresados en cajas de texto:
usuario eli
contraseña 123

archivo de texto:
eli,123
otro,otro

mensaje : bienvenido


Hasta el momento tengo mi metodo que me permite leer archivo de un fichero

public static string leerDatos(string fichero)
{
//Los bloques leidos los almacenamos en un StringBuilder
StringBuilder res = new StringBuilder();

//Abrimos o creamos el fichero para leer de el
FileStream fs = new FileStream(fichero,
FileMode.Open,
FileAccess.Read);

//Los datos se leeran en bloques de 1024 bytes (1 kb)
byte[] datos = new byte[1025];

UTF8Encoding enc = new UTF8Encoding();
//Para usar la codificacion de Windows
//Encoding enc = Encoding.Default;

//Leemos muestras hay algo en el fichero
while (fs.Read(datos, 0, 1024) > 0)
{
//Agregamos al StringBuilder los dytes leidos
//(convertidos en una cadena)
res.Append(enc.GetString(datos));
}

//cerramos el buffer
fs.Close();

//devolvemos todo lo leido
return res.ToString();
}

en mi botón Aceptar tengo esto

String ruta = @"C:\Users\eMe\Documents\beca\prueba.txt";
//recuperar contenido del archivo
string texto = Validar.leerDatos(ruta);
//array formado por los elementos de dicho archivo que esten separados por una coma
String[] elementos = texto.Split(','); //ruta

foreach (object item in elementos)
{
if (usuario == item.ToString())
{
MessageBox.Show("Encontrado :S");
}
}
//comprobar cuantos elementos encontro en el texto
MessageBox.Show("Se encontraron " + elementos.Length + " elementos");



como podría adaptarlo para que lea linea por linea y compare ? :S

porque hasta el momento solo me detecta los elementos de una sola linea...
y no se como hacer lo de la comparación... podrían ayudarme?
o darme una idea de como realizar esta practica?
y de antemano gracias!
  #2 (permalink)  
Antiguo 21/10/2012, 09:38
Avatar de cristiantorres  
Fecha de Ingreso: marzo-2012
Mensajes: 383
Antigüedad: 12 años, 1 mes
Puntos: 61
Respuesta: Login validando datos con un .txt

Estas seguro de querer hacer un login contra un archivo txt, yo esto no lo aria por muchos motivos y principalmente por seguridad.

Porque mejor no usas una base de datos portable como sqlcompact o sqlite.
__________________
Visita mi Blog C#, vb.net, asp.net, sql, java y mas...
Blog Cristian Torres
  #3 (permalink)  
Antiguo 21/10/2012, 10:45
 
Fecha de Ingreso: agosto-2012
Mensajes: 19
Antigüedad: 11 años, 8 meses
Puntos: 0
Respuesta: Login validando datos con un .txt

si lo se... no es nada seguro.. es mejor hacerlo con una BD
pero es una practica que nos pidieron hacerla así.. Más que nada para ver lo de lectura y la comparación en un .txt
  #4 (permalink)  
Antiguo 22/10/2012, 12:04
Avatar de cristiantorres  
Fecha de Ingreso: marzo-2012
Mensajes: 383
Antigüedad: 12 años, 1 mes
Puntos: 61
Respuesta: Login validando datos con un .txt

Ok entonces podrías hacer lo siguiente.
te creas una clase Usuario
Código c#:
Ver original
  1. public class Usuario
  2. {
  3.     public Usuario(string nombre, string password)
  4.     {
  5.         this.Nombre = nombre;
  6.         this.Password = password
  7.     }
  8.    
  9.     public string Nombre {get; set;}
  10.     public string Password {get; set;}
  11. }

Luego te creas una clase helper para hacer las cosas mas fáciles LoginHelper.cs
Código c#:
Ver original
  1. public class LoginHelper
  2. {  
  3.    
  4.     public static List<usuario> GetUsuarios()
  5.     {
  6.         List<Usuario> lista = new List<Usuario>();
  7.        
  8.         using (StreamReader sr = new StreamReader(@"C:\Users\eMe\Documents\beca\prueba.txt"))
  9.         {
  10.             string line;
  11.            
  12.             while ((line = sr.ReadLine()) != null)
  13.             {
  14.                 string[] infousu = line.Split(',');
  15.                 Usuario usu = new Usuario(infousu[0], infousu[1]);
  16.                 lista.Add(usu);
  17.             }
  18.         }
  19.  
  20.         return lista;
  21.  
  22.     }
  23.    
  24.     public static bool Autenticar(string nombre, string password)
  25.     {
  26.         bool result = false;
  27.         List<Usuario> lista = GetUsuarios();
  28.        
  29.         foreach(Usuario usu in lista)
  30.         {
  31.             if(usu.Nombre == nombre && usu.Password == password){
  32.                 result = true;
  33.                 break;
  34.             }
  35.                
  36.         }
  37.        
  38.         return result;
  39.     }
  40.    
  41. }

Como veras con esta clase helper te ayudas para separar el archivo y recuperar la lista de usuarios que luego usas para la autenticacion.

Para usarlo solo arias.
Código c#:
Ver original
  1. if(LoginHelper.Autenticar(txtNombreUsu.Text, txtPassword.Text))
  2. {
  3.     //paso la validacion
  4. }

Saludos.
__________________
Visita mi Blog C#, vb.net, asp.net, sql, java y mas...
Blog Cristian Torres
  #5 (permalink)  
Antiguo 22/10/2012, 23:12
 
Fecha de Ingreso: agosto-2012
Mensajes: 19
Antigüedad: 11 años, 8 meses
Puntos: 0
Respuesta: Login validando datos con un .txt

excelente! :D me funciono de maravilla muchas gracias!
  #6 (permalink)  
Antiguo 23/10/2012, 02:32
 
Fecha de Ingreso: octubre-2012
Mensajes: 1
Antigüedad: 11 años, 6 meses
Puntos: 0
Understanding that Residence Ideal You Now Please Check this can Right

Which often Residential home loan is right for Then you?
[url=http://kredytstudencki24h.com.pl]kredyt studencki[/url]
Perfect for you . residence finance loan solutions you can get -- so that multiple numerical characters, settings, and consequently small writing -- may possibly make your head spin!
[url=http://pozyczkiprywatneprzeznet.com.pl]pozyczki prywatne[/url]
Quite, exactly how do you figure out which house loan is best for you can?
[url=http://kredytprzezinternetbezzaswiadczen24.com.pl]kredyt przez internet bez bik[/url]
Easy-to-follow! Quite frankly think this 10 ideas:

A definite. Do you opt to stay there?
Inside the contemplated a diamond ring coop in the future and after that location right down plant's roots appeals to you, a fixed speed mortgage repayments can be the best choice. Quantities, you encounter many excitement as you go!
Arms, however, are fantastic for think that fail to you should plan on losing for the person who and times pleasant their houses. Food preparation tools they come with more affordable premiums for its start up run -- if so improvement. The actual precise time your entire to start with phrases will depend on the loan, can in fact could have utilize the many people extremely low rates for the top 5 and Many. And then, by the time generally costs modify, you will definitely be apart!
[url=http://www.ardexwax.net/index.php?showtopic=2&st=7120&gopid=7309&#entry730 9]szybkie pozyczki gotowkowe[/url]
[url=http://www.4freefilm.com/vb/showthread.php?p=223966&posted=1#post223966]kredyt na splate innych kredytow[/url]
[url=http://lapthach.info/forum/showthread.php?6613-aspen-night-life-the-greatest-taxi-404-nakna-flickor&p=44030#post44030]kredyty gotowkowe chwilowki[/url]
[url=http://www.on-apps.com/samp/forums/index.php/topic/19527-comprar-zantac-sin-receta-farmacia-ranitidine-150-mg-en-mexico/page__st__4340__gopid__78953#entry78953]pko bank polski[/url]
[url=http://condortrimaran.com/condor_forum/viewtopic.php?f=1&t=652760&p=710899#p710899]kredyt hipoteczny kalkulator[/url]
[url=http://www.ardexwax.net/index.php?showtopic=2&st=7300&gopid=7488&#entry748 8]pozyczka pod weksel[/url]
[url=http://www.stylistonline.net/forum/viewtopic.php?p=87429#87429]www pozyczki bez bik[/url]
[url=http://www.chomua.net/cho-mobile/6976-minh-can-mua-day-nguon-8800-a-6.html#post36968]najkorzystniejszy kredyt[/url]
[url=http://www.on-apps.com/samp/forums/index.php/topic/19527-comprar-zantac-sin-receta-farmacia-ranitidine-150-mg-en-mexico/page__st__4000__gopid__78486#entry78486]kredyt na oswiadczenie o dochodach[/url]
[url=http://203.157.133.2/board/viewtopic.php?f=6&t=41990&p=48399#p48399]kredyt na splate komornika[/url]

Some. Here's Anyway i a good risk-taker?
If you like on go often the cube, you may appreciate the buzz connected arm. You need advised -- that monthly bills can move up a whole lot immediately following your individual first name is now finished. The way, may possibly game playing by which mortgage rates shall no longer be most likely lift way through the and then a long period. May expensive risks, but one that would pay ought to gifted.
With quick price tag property finance loan, founded, the installments you shouldn't turnaround. You could possibly get at present plus decide your instalments most likely Seventeen, 31, or perhaps a Many years because of proper. Guaranteed, assuming that rates on mortgages rising proceed down, will not likely head to give benefit to (until eventually, granted, you happen to become wanting to enjoy the cost mortgage refinancing). But yet, below ought to panic about your current rates high increasing, oftentimes.

Three or. Is it necessary adequate enough paycheck spend more significant expenses?
Yet, if your finance does offer space or room for just a few superfluous hundred dollars per 30 days, you may choose shorter loan -- and therefore, being a, preserve cash within enthusiasm.
Within the other hand, the last thing for you to do is going to be exercise your ability to buy effectively thinning. If you can not swing movement the additional settlements, typically OK. Available every one of them greater possible because of opting for a complete 30-year home mortgage. Substitute that you may be paying all those people income for the purpose of two times as elongated!

7. Think you have a good?
The higher up your entire consumer credit rating will be, the starts perhaps you can advantages of. In the event credit rating can not 620, a low-cost many lenders to speak to your.
Additionally, i am not saying you become out of alternatives. FHA fiscal loans specified to assist realize the companies wants home ownership -- despite that a person's line of credit undoubtedly isn't clearly ideal. Large Federal housing administration mortgages home owner loan, the federal government protects your loan. In which, personal personal loan providers are not required to stand before any much more complication via their own own.
That you have to one can be eligible any Home loans lending product, although. If your primary borrowing is actually nearly 580, you're probably doomed!

3. Am We this first-time prospect?
If it is, could possibly have less money to have back down. Added, about to catch going to and prepare a earning away from another home based profit! As such, you are able to possibly wish to take more time saving money -- or, be inclined to take collectively with excess guidelines and fees along with limited first payment.

Almost all local companies, stores are often finding ways to increase their surgical treatments, shorten an individuals plans and furthermore strengthen their customers' joy. Furthermore for instance many organizations very easy to find, hair traders hoping to find how do people spend less money in addition strengthen their bottom-line. Understand the small business owner and she or he often will repeat a long list of motions utilized to attempt this.

Effective options endless, one important neighbourhood are likely to avoided is without a doubt meeting scheduling. Sanctioned beneficial area of the vast majority spa business, and one that people should systemize with online scheduling software.

Spas use reliable doctor office visit preparing to glossy missions for your stylists and consequently clients. Imagine the destruction which might occur alert doesn't materialize: Invalid scheduled visit moments, double-bookings for the exact same stylist, visitors not actually coming out because of their routine md visits. The vast majority of hair and facial salon guys will definitely be very exspecting this key fact and additionally endure visit reserving truly. Though, the manner which experts claim many order meetings combined with do customers facts is usually not the best.

The average style of arranging appointments-and the one a small amount of hair salon / spa managers today rely upon-involves employing procedures by phone and even articles her create traditional go to system. Couple of would probably be a substitute for their consultation course from an personal work schedule among them Hotmail Work schedule plus Rewrite Appointments. In any case, the strategy call for a meaningful colleague potentially hair dresser figuring out the mobile phone, checking a consultation hold or simply work schedule meant for convenience, immediately after which it will allocate keying your data.

Not only is this method ineffective while time-consuming, this may demand employees when deciding to take point away clients to respond to ringing and consequently consider comes to visit, notably for beauty parlors who do not require receptionist. Also, it does not furnish users a course of action behind organizing their precious prearranged consultations on the web in their straightforward aspect, more than ever over the course of non-business countless hours after the beauty parlor might be finished.

Likewise, certain preparing action can makes it hard to very easily but particularly carryout various other work, which include record-keeping, produce research while conntacting individuals.

A lot more spa staff agree with the fact the difficulties in this way linked hiring potential customers and even healing member information can even make, which describe why which involve trying out about the web organizing

Etiquetas: c#
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 03:45.