StreamReader failing to read second line - c#

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];
}
}

Related

Read 2 lines by 2lines in textfile

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();

read .csv file into 1D array c#

I would like to convert this code from java to C#
I need to write line by line from csv and store it in an array?
String csvFile = "data.csv";
String line = "";
String cvsSplitBy = ",";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile)))
{
while ((line = br.readLine()) != null)
{
// use comma as separator
String[] data = line.split(cvsSplitBy);
System.out.println(Integer.parseInt(data[0]) + " "+data[1] + " "+data[2] );
}
}
catch (IOException e)
{
e.printStackTrace();
}
Any suggestions?
If you are trying to parse each record/row into array, this might help.
using (StreamReader sr = new StreamReader("maybyourfilepat\data.csv"))
{
string line = sr.ReadLine();
//incase if you want to ignore the header
while (line != null)
{
string[] strCols = line.Split(',');
line = sr.ReadLine();
}
}

Can I programatically copy my html selection

I have a html document that after being parsed contains only formatted text.I was wondering if it is possible to get its text like I would do if I was mouse-selecting it + copy + paste in new Text Document?
I know that this is possible in Microsoft.Office.Interop where I have .ActiveSelection property that selects the content of the open Word.
I need to find a way to load the html somehowe(maybe in a browser object) and then copy all of its content and assign it to a string.
var doc = new HtmlAgilityPack.HtmlDocument();
var documetText = File.ReadAllText(myhtmlfile.html, Encoding.GetEncoding(1251));
documetText = this.PerformSomeChangesOverDocument(documetText);
doc.LoadHtml(documetText);
var stringWriter = new StringWriter();
AgilityPackEntities.AgilityPack.ConvertTo(doc.DocumentNode, stringWriter);
stringWriter.Flush();
var titleNode = doc.DocumentNode.SelectNodes("//title");
if (titleNode != null)
{
var titleToBeRemoved = titleNode[0].InnerText;
document.DocumentContent = stringWriter.ToString().Replace(titleToBeRemoved, string.Empty);
}
else
{
document.DocumentContent = stringWriter.ToString();
}
and then I return the document object.The problem is that the string is not always formatted as I want it to be
You should be able to just use StreamReader and as you read each line just write it out using StreamWriter
Something like this will readuntil the end of your file and save it to a new one. If you need to do extra logic in the file I have a comment inserted to let you know where to do all that.
private void button4_Click(object sender, EventArgs e)
{
System.IO.StreamWriter writer = new System.IO.StreamWriter("C:\\XXX\\XXX\\XXX\\test2.html");
String line;
using (System.IO.StreamReader reader = new System.IO.StreamReader("C:\\XXX\\XXX\\XXX\\test.html"))
{
//Do until the end
while ((line = reader.ReadLine()) != null) {
//You can insert extra logic here if you need to omit lines or change them
writer.WriteLine(line);
}
//All done, close the reader
reader.Close();
}
//Flush and close the writer
writer.Flush();
writer.Close();
}
You can also save it to a string then just do whatever you want to with it. You can use new lines to keep the same format.
EDIT The below will tke into account your tags
private void button4_Click(object sender, EventArgs e)
{
String line;
String filetext = null;
int count = 0;
using (System.IO.StreamReader reader = new System.IO.StreamReader("C:\\XXXX\\XXXX\\XXXX\\test.html"))
{
while ((line = reader.ReadLine()) != null) {
if (count == 0) {
//No newline since its start
if (line.StartsWith("<")) {
//skip this it is formatted stuff
}
else {
filetext = filetext + line;
}
}
else {
if (line.StartsWith("<"))
{
//skip this it is formatted stuff
}
else
{
filetext = filetext + "\n" + line;
}
}
count++;
}
Trace.WriteLine(filetext);
reader.Close();
}
}

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