rintintin
rintintin

Reputation: 21

Read credentials in text file for program c#?

This is my program, and it work correctly if i put username and password :

 try
 {

     var url = @"https://mail.google.com/mail/feed/atom";
     var User = username;
     var Pasw = password;
     var encoded = TextToBase64(User + ":" + Pasw);
     var myweb = HttpWebRequest.Create(url) as HttpWebRequest;
     myweb.Method = "POST";
     myweb.ContentLength = 0;
     myweb.Headers.Add("Authorization", "Basic " + encoded);
     var response = myweb.GetResponse();
     var stream = response.GetResponseStream();
     textBox1.Text += ("Connection established with" + User + Pasw);
 }
 catch (Exception ex)
 {
     textBox1.Text += ("Error connection. Original error: " + ex.Message);

now i want read string of texfile, split them and read username and password like this format: username:password . There is my code at the moment:

 Stream myStream = null;
 OpenFileDialog openFileDialog1 = new OpenFileDialog();

 openFileDialog1.InitialDirectory = "c:\\";
 openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
 openFileDialog1.FilterIndex = 2;
 openFileDialog1.RestoreDirectory = true;

 string file_name = "";
 file_name = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + file_name;

 if (openFileDialog1.ShowDialog() == DialogResult.OK)
 {

      try
      {        
           if ((myStream = openFileDialog1.OpenFile()) != null)
           {

               using (StringReader reader = new StringReader(file_name))
               {
                    // Loop over the lines in the string.
                    int count = 0;
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                         string[] data = line.Split(':');
                         string username = data[0].Trim();
                         string password = data[1].Trim();

                         count++;
                 /*       Console.WriteLine("Line {0}: {1}", count, line);    */
               }
               reader.Close();
           }
       }
  }
  catch (Exception ex)
  {
       MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
  }

Upvotes: 1

Views: 2077

Answers (2)

Steve
Steve

Reputation: 216313

You open the file selected by the user, but then try to read from a variable file_name that is not the name of a file but the name of a well kwown folder. Perhaps you want this

try
{        
    if (openFileDialog1.FileName != string.Empty)
    {
        using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
        {
           ....
        }
    }
}

In this same code you use a StringReader, but instead you need a StreamReader to read from a file. StringReader takes the value passed in its constructor and return in the ReadLine call. Then you split the line at the colon but of course this is not the content of your file.

There are other problems in your code. For example, what do you do with the username and password loaded from the line? They are declared as local variables and not used anywhere, so at the next loop they are overwritten and lost.

So, a UserData class could be a possible answer

public class UserData
{ 
    public string UserName {get; set;}
    public string Password {get; set;}
}

and declare at the form global level an

 List<UserData> data = new List<UserData>

and in your loop

public void button1_Click(object sender, EventArgs e)    
{    
    try
    {        
        if (openFileDialog1.FileName != string.Empty)
        {
            using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
            {
                int count = 0;
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    UserData d = new UserData();
                    string[] parts = line.Split(':');
                    d.UserName = parts[0].Trim();
                    d.Password = parts[1].Trim();
                    data.Add(d);
                }

                // At the loop end you could use the List<UserData> like a normal array
                foreach(UserData ud in data)
                {
                    Console.WriteLine("User=" + dd.UserName + " with password=" + dd.Password);
                }
            }
        }
    }
}


public void button2_Click(object sender, EventArgs e)
{
    try
    {
         if(data.Count() == 0)
         {
             MessageBox.Show("Load user info first");
             return;
         }

         var url = @"https://mail.google.com/mail/feed/atom";
         var encoded = TextToBase64(data[0].UserName + ":" + data[0].Password);         
         .....

A warning note. Of course this is just demo code. Remember that in a real scenario saving passwords in clear text is a big security concern. The impact of this is relative to the context of your application but should not be downplayed. A better course of action is to store an hashing of the password values and apply the same hashing function when you need to compare password

Upvotes: 4

Andrey Korneyev
Andrey Korneyev

Reputation: 26876

You are creating StringReader from file_name varialbe, which is (according to your code)

string file_name = "";
        file_name = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + file_name;

and points to nothere.

Also you have stream created for file being selected with open file dialog but you haven't use this stream.

Upvotes: 1

Related Questions