Read 2 lines by 2lines in textfile - c#

Suppose that the method ReadUser below is reading the user and password in the textfile. The problem is, it doesn't read the rest of the textfile after reading the first 2 lines. How to solve this issue?
*Edit: how do I read first 2 lines then another 2 lines in the textfile ?
public override void ReadUser()
{
user = base.UserID;
password = base.Password;
using (StreamReader sr = new StreamReader(File.Open("C:\\Users\\user\\Documents\\Projects\\AdministratorModule//userTextFile.txt", FileMode.Open)))
{
user1 = sr.ReadLine();
password1 = sr.ReadLine();
sr.Close();
if (user == user1 && password == password1)
{
Console.WriteLine("Login Successfull");
}
else
{
Console.WriteLine("Login Failed");
}
}
}

simple a basic logic
int currentLine = 0;
//no need use close method with using
using (StreamReader sr = new StreamReader(File.Open("C:\\Users\\user\\Documents\\Projects\\AdministratorModule//userTextFile.txt", FileMode.Open)))
{
string line;
while ((line = sr.ReadLine()) != null)
{
switch (++currentLine)
{
case 1: user1 = line; break;
case 2: password1 = line; break;
case 3: otherVariable = line; break;
case 4: yetAnotherVariable = line; break;
......
}
//rest of your logic
}
}
However, if for some reason you need to store all the strings in an array, you're best off just using File.ReadAllLines();

Related

StreamReader failing to read second line

I am using a StreamReader to read out the Username and Password from a .csv file (I'm just trying this out because I'm new to C#). For some reason, if I press sign in it works for the account in the first line of the file but not the second one. Anyone can help?
Register Code (Writer):
try
{
using (StreamWriter sw = new StreamWriter("C:\\GameLauncherKarakurt\\users.csv", true))
{
sw.WriteLine(tbxUsername.Text + ';' + tbxPassword.Text);
sw.Close();
}
}
catch
{
// Do nothing
}
Sign-in Code (Reader):
string username;
string password;
bool usernameCorrect = false;
bool passwordCorrect = false;
// Username
try
{
using (StreamReader sr = new StreamReader("C:\\GameLauncherKarakurt\\users.csv"))
{
username = sr.ReadLine();
string[] usernameSplit = username.Split(';');
string user = usernameSplit[0];
while (username != null)
{
if (tbxUsername.Text == user)
{
usernameCorrect = true;
break;
}
else
{
username = sr.ReadLine();
}
}
sr.Close();
}
}
catch
{
}
// Password
try
{
using (StreamReader sr = new StreamReader("C:\\GameLauncherKarakurt\\users.csv"))
{
password = sr.ReadLine();
string[] passwordSplit = password.Split(';');
string pass = passwordSplit[1];
while (password != null)
{
if (tbxPassword.Text == pass)
{
passwordCorrect = true;
break;
}
else
{
password = sr.ReadLine();
}
}
sr.Close();
}
}
catch
{
}
if (usernameCorrect == true && passwordCorrect == true)
{
pnlMenu.Visible = true;
tbxUsername.Clear();
tbxPassword.Clear();
}
You are not keeping the structure of CSV file. all couples of user and password must be separated by comma (",") and not by a new line,
Add a comma after each user and password couple.
Use Write() and not WriteLine().
private void Write()
{
try
{
using (StreamWriter sw = new StreamWriter("C:\\GameLauncherKarakurt\\users.csv", true))
{
// next time you add user and pass word you need to concatenate with ","
sw.Write(tbxUsername.Text + ';' + tbxPassword.Text + ",");
sw.Close();
}
}
catch()
{
// Do nothing
}
}
Here is one way to read the file. Use ReadToEnd() and split all the user and password couples to an array, each couple will be at a different index:
using (StreamReader sr = new StreamReader("C:\\GameLauncherKarakurt\\users.csv"))
{
var rows = sr.ReadToEnd();
string[] splitted = rows.Split(',');
}
Now you can split again each index of the array by the ";" separator,
keep in mind that there are some improvements you can do to your "matching"/authentication logic.
Once your file has been created, you can read the user and password from each line using the statement below:
using (StreamReader sr = new StreamReader(""C:\\GameLauncherKarakurt\\users.csv""))
{
while (!sr.EndOfStream)
{
strLine = sr.ReadLine();
string[] usernameSplit = strLine.Split(';');
string user = usernameSplit[0];
string password = usernameSplit[1];
}
}

c# function inside while won't cycle

hi everybody i have this code
StreamReader reader = new StreamReader("C:\\Users\\lorenzov\\Desktop\\gi_pulito_neg.txt");
string line = reader.ReadLine();
string app = "";
int i = 0;
while (line != null)
{
i++;
line = reader.ReadLine();
if (line != null)
{
int lunghezza = line.Length;
}
Console.WriteLine(i);
System.Threading.Thread.Sleep(800);
string ris= traduttore.traduci(targetLanguage, line);
// Console.WriteLine(line);
// Console.WriteLine(ris);
// Console.Read();
// app = app + ris;
// System.Threading.Thread.Sleep(50);
File.AppendAllText(#"C:\Users\lorenzov\Desktop\gi_tradotto_neg.txt", ris + Environment.NewLine);
}
the fact is that i have a txt file which i want to translate with this function traduci(targetLanguage,line), the function is ok, i want to translate each line into another file, while is looping the function is blocking at the first loop, if i insert consonle.read() when i press enter the function works...ho can i do? thank you all!
Your code is pretty messy. I would suggest the following method to loop over the StreamReader lines:
using (StreamReader reader = new StreamReader("C:\\Users\\lorenzov\\Desktop\\gi_pulito_neg.txt"))
{
string line;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
// ... process the line
}
}
If ReadLine returns a null, your code will break. better structure:
StreamReader reader = new StreamReader("C:\\Users\\lorenzov\\Desktop\\gi_pulito_neg.txt");
string line;
string app = "";
int i = 0;
while ((line = reader.ReadLine()) != null)
{
i++;
int lunghezza = line.Length;
Console.WriteLine(i);
System.Threading.Thread.Sleep(800);
string ris= traduttore.traduci(targetLanguage, line);
// Console.WriteLine(line);
// Console.WriteLine(ris);
// Console.Read();
// app = app + ris;
// System.Threading.Thread.Sleep(50);
File.AppendAllText(#"C:\Users\lorenzov\Desktop\gi_tradotto_neg.txt", ris + Environment.NewLine);
}
The code as it stands will skip over the first line, as you use ReadLine() twice prior to fist use.
You can restructure the code as
using (StreamReader reader = new StreamReader(#"C:\Users\lorenzov\Desktop\gi_pulito_neg.txt"))
using (StreamWriter writer = new StreamWriter(#"C:\Users\lorenzov\Desktop\gi_tradotto_neg.txt"))
{
string line = reader.ReadLine();
while(line != null)
{
System.Threading.Thread.Sleep(800);
string ris = traduttore.traduci(targetLanguage, line);
writer.WriteLine(ris);
line = reader.ReadLine();
}
}

windows forms array to file

Newbie here, currently studying C# course and totally new to coding and stuff.
Sorry if this question is already been asked, I've been googling for quite some time and still unable to find a proper answer or anything near it.
Question being simple. I have an array that contains string needs to be saved onto a file, needs to be retrieved when required.
example
string[] item_name = {"abc", "def", "ghi"};
float[] item_cost = {30f,20f,10f};
int[] item_qty = {10,20,30};
How do i go about saving all these data into a file (e.g .txt) and then retrieve at a button_click command?
try this.... u will get answer....
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Select your option: 1 for Write, 2 for Read, 3 for Search, others for exit");
int flag = Convert.ToInt32(Console.ReadLine());
if (flag != 1 && flag != 2 && flag != 3) break;
switch (flag)
{
case 1:
{
StreamWriter SW = new StreamWriter(#"C:\test.txt");
while (true)
{
Console.WriteLine("Enter some value for inset into text file, 0 for exit\n");
string temp = Console.ReadLine();
if (temp != "0")
{
SW.WriteLine(temp);
}
else
{
break;
}
}
//SW.Dispose();
SW.Close();
break;
}
case 2:
{
StreamReader SR = new StreamReader(#"C:\test.txt");
while (true)
{
Console.WriteLine(SR.ReadLine());
if (SR.EndOfStream == true)
break;
}
SR.Dispose();
SR.Close();
break;
}
case 3:
{
Console.Write("entre ur value:\t");
string value = Console.ReadLine();
StreamReader SR = new StreamReader(#"C:\test.txt");
bool flg = false;
while (true)
{
if (value == SR.ReadLine())
{
Console.WriteLine(value + " was found in ur text");
flg = true;
break;
}
if (SR.EndOfStream == true)
break;
}
if (flg != true)
{
Console.WriteLine("Sorry not found");
}
SR.Dispose();
SR.Close();
break;
}
default:
{
break;
}
}
}
}

Reading input value from textbox, fetching the data from Textfile and displaying the result

I need help in searching the text file. I have manage to store the input values to Textfile with ":" separator.
And my result text box is like
friend1:126457890
friend2:123487012
Friend3:798461598
and now I want to search the text file and display result in labels/textbox(read only)
Here is my code to search
private void btn_search_search_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(txt_search.Text))
{
lbl_search_error.Text = "Please Enter name to search";
}
else
{
StreamReader sr = new StreamReader(#"path.txt");
string line;
string searchkey = txt_search.Text;
sr.ReadToEnd();
while ((line = sr.ReadLine()) != null)
{
if (line.Contains(searchkey))
break;
}
sr.Close();
string[] data = line.Split(':');
txt_result_name.Text = data[0];
txt_result_phno.Text = data[1];
}
}
catch (Exception ex)
{
lbl_search_error.Text = ex.Message;
}
}
but I get
Object reference not set to an instance of an object
I tried to keep break point and chk, error is in this line
string[] data = line.Split(':');
Please help resolving
Thank you for your time
Delete the line sr.ReadToEnd();
Let me give you a different approach using regular expression:
private void btn_search_search_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("Some file");
string line = sr.ReadLine();
string name="";
string number="";
while (line != null)
{
var m = Regex.Match(line, #"([\w]+):([\d]+)<br>");
if (m.Success)
{
name = m.Groups[1].Value;
number = m.Groups[2].Value; // use this name and number variables as per your need
line = sr.ReadLine();
}
else
{
line = sr.ReadLine();
}
}
}
This is a way to go about the problem. Ask any questions if you have
You are getting this error because the value of line is null in: string[] data = line.Split(':');
Take a string variable called temp and assign the value of line to temp in the while loop. Later use this variable instead of line.
Do like this:
private void btn_search_search_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(txt_search.Text))
{
lbl_search_error.Text = "Please Enter name to search";
}
else
{
StreamReader sr = new StreamReader(#"path.txt");
string line;
string searchkey = txt_search.Text;
sr.ReadToEnd();
string temp;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains(searchkey))
{
temp = line;
break;
}
}
sr.Close();
string[] data = temp.Split(':');
txt_result_name.Text = data[0];
txt_result_phno.Text = data[1];
}
}
catch (Exception ex)
{
lbl_search_error.Text = ex.Message;
}
}

Using StreamReader to check if a file contains a string

I have a string that is args[0].
Here is my code so far:
static void Main(string[] args)
{
string latestversion = args[0];
// create reader & open file
using (StreamReader sr = new StreamReader("C:\\Work\\list.txt"))
{
while (sr.Peek() >= 0)
{
// code here
}
}
}
I would like to check if my list.txt file contains args[0]. If it does, then I will create another process StreamWriter to write a string 1 or 0 into the file. How do I do this?
Are you expecting the file to be particularly big? If not, the simplest way of doing it would be to just read the whole thing:
using (StreamReader sr = new StreamReader("C:\\Work\\list.txt"))
{
string contents = sr.ReadToEnd();
if (contents.Contains(args[0]))
{
// ...
}
}
Or:
string contents = File.ReadAllText("C:\\Work\\list.txt");
if (contents.Contains(args[0]))
{
// ...
}
Alternatively, you could read it line by line:
foreach (string line in File.ReadLines("C:\\Work\\list.txt"))
{
if (line.Contains(args[0]))
{
// ...
// Break if you don't need to do anything else
}
}
Or even more LINQ-like:
if (File.ReadLines("C:\\Work\\list.txt").Any(line => line.Contains(args[0])))
{
...
}
Note that ReadLines is only available from .NET 4, but you could reasonably easily call TextReader.ReadLine in a loop yourself instead.
You should not add the ';' at the end of the using statement.
Code to work:
string latestversion = args[0];
using (StreamReader sr = new StreamReader("C:\\Work\\list.txt"))
using (StreamWriter sw = new StreamWriter("C:\\Work\\otherFile.txt"))
{
// loop by lines - for big files
string line = sr.ReadLine();
bool flag = false;
while (line != null)
{
if (line.IndexOf(latestversion) > -1)
{
flag = true;
break;
}
line = sr.ReadLine();
}
if (flag)
sw.Write("1");
else
sw.Write("0");
// other solution - for small files
var fileContents = sr.ReadToEnd();
{
if (fileContents.IndexOf(latestversion) > -1)
sw.Write("1");
else
sw.Write("0");
}
}
if ( System.IO.File.ReadAllText("C:\\Work\\list.txt").Contains( args[0] ) )
{
...
}
The accepted answer reads all file in memory which can be consuming.
Here's an alternative inspired by VMAtm answer
using (var sr = new StreamReader("c:\\path\\to\\file", true))
for (string line; (line = sr.ReadLine()) != null;) //read line by line
if (line.Contains("mystring"))
return true;

Categories

Resources