1

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);
  }
tshepang
  • 12,111
  • 21
  • 91
  • 136
rintintin
  • 21
  • 5

2 Answers2

4

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

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
  • ok but in program it say that username,password don't exist in the current context – rintintin Sep 16 '14 at 12:27
  • But how many lines are present in your file? The code above creates a list of these lines transformed in a UserData instances. Of course you need to pass the values of one of these instances to your method above. Something like `var encoded = TextToBase64(data[0].UserName + ":" + data[0].Password);` – Steve Sep 16 '14 at 12:37
  • can't. it give me error. but i would know how can run "var User = username; error like: don't exist in the current context – rintintin Sep 16 '14 at 12:40
  • Sorry but without seeing the relationship between the two blocks of code of your question is not possible to resolve this problem. Could you update your question showing in which method is present the first block of code and in which method is presente the second one? Also after you retrieve the values from the file how do you call the first block of code? – Steve Sep 16 '14 at 12:45
  • Well, now it is clear. The List data should be made public at the form global level. So you could use it in the button that initializes the gmail connection. I will update the answer – Steve Sep 16 '14 at 13:36
  • Yea but same problem: it say that "data" not exists in current context – rintintin Sep 16 '14 at 14:08
  • Did you move the declaration of `List data = new....` at the form global level ? (meaning outside any method but inside the form class code block) – Steve Sep 16 '14 at 14:12
  • 1
    Solved all. just now a little issue i think, don't know if it should be like that: var count never be used. – rintintin Sep 16 '14 at 15:57
  • 1
    Tried with that: foreach (UserData ud in data) { textBox1.Text += (ud.username + ud.password); } and return path of file, (directory) not username and password. (in button 1) – rintintin Sep 16 '14 at 16:16
  • And when start on button 2 i got an error like this (transleted fron italian, italian error:Richiesto valore non negativo e minore della dimensione della raccolta. Nome parametro: index ): Index not included in (intervallo is pretty vague as a term) interval/range. Requested a non-negative value which is also smaller than the folder's size – rintintin Sep 16 '14 at 16:34
  • Did you write the check for `data.Count() == 0`? – Steve Sep 16 '14 at 16:37
  • i copied all text in my project: if(data.Count() == 0) (button2) int count = 0; (button1) – rintintin Sep 16 '14 at 20:24
  • I have no idea on what is your problem. If you are willing to share and your project is not too big you could zip it and upload it on a online storage service like GDrive, OneDrive, DropBox and then share the link here. I will take a look. – Steve Sep 16 '14 at 20:55
  • Ok. however i would that program try to connect in a loop with all account on list just with press button 2. wait a moment for zip – rintintin Sep 16 '14 at 20:56
  • Here it is download zip mediafire http://www.mediafire.com/download/alnbh2aoi4iz39x/forSteve.zip – rintintin Sep 16 '14 at 20:59
  • I can't believe that I haven't seen it. You are using a `StringReader` not a `StreamReader`. That class takes your filename variable as its input (`C:\\tempnames.txt` for example) not the content of the file. So the code splits the `filename` string at the drive letter `C` and take it as the user name and the remainder of the filename as password. Change it to StreamReader and it reads the file correctly – Steve Sep 16 '14 at 22:02
  • it work perfectly, thanks a lot for all help steve... just a last question, if i want display result in textbox in vertically? like linebreak for all user data how do? – rintintin Sep 16 '14 at 22:15
  • Now it's time to post a new question. Past midnight in Italy now....Good night and see you again on SO... Ciao. – Steve Sep 16 '14 at 22:22
  • Here new question :l nobody want answer me http://stackoverflow.com/questions/25888801/loop-function-by-button-c – rintintin Sep 17 '14 at 13:17
1

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.

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71