StreamReader Multiple lines - c#

I am trying to figure out how to read multiple lines whith StreamReader. I have a text file with a list of commands inside it that I need to read from. My code works, however it will only read the first line. This causes me to have to move all my commands to a single line with a space between them. This is not a very tidy way of doing this seeing as I need to leave comments next to the commands. Example: CONNECT: "Connects to given IP."
public void ConsoleEnter_KeyDown(object sender, KeyEventArgs e)
{
string line;
if (e.KeyCode == Keys.Enter)
{
// Read the file and display it line by line.
StreamReader file = new StreamReader("C:\\Users\\Home\\Desktop\\commands.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(ConsoleEnter.Text))
{
COMBOX.Items.Add(ConsoleEnter.Text);
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
else
{
COMBOX.Items.Add("Invalid Command");
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
}
}
}

This is what am using in one of my app and its working fine hope it'll help you out.......
if (TxtPath.Text != string.Empty)
{
StreamReader srr = new StreamReader(TxtPath.Text);
try
{
ss = srr.ReadToEnd().Split('\n');
MessageBox.Show("File Successfully Loded in Memory \n" + TxtPath.Text, "System Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception)
{
throw new Exception("File are not readable or write protacted");
}
LblLineCount.Text = ss.Count().ToString();
}
else
{
MessageBox.Show("Please Browse any Log File 1st", "System Manager", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
you can also trim the
.Split('\n')
to take all data in single line, i can't try it right now but if check it will get u out of stuck...........

u should empty the variable after the loop, not inside the loop
public void ConsoleEnter_KeyDown(object sender, KeyEventArgs e)
{
string line;
if (e.KeyCode == Keys.Enter)
{
// Read the file and display it line by line.
StreamReader file = new StreamReader("C:\\Users\\Home\\Desktop\\commands.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(ConsoleEnter.Text))
{
COMBOX.Items.Add(ConsoleEnter.Text);
}
else
{
COMBOX.Items.Add("Invalid Command");
}
}
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
}

public void ConsoleEnter_KeyDown(object sender, KeyEventArgs e)
{
string line;
string path = #"C:\\Users\\Home\\Desktop\\commands.txt";
WebClient client = new WebClient();
System.IO.Stream stream = client.OpenRead(path);
System.IO.StreamReader str = new StreamReader(stream);
string Text=str.ReadToEnd();
string[] words = Text.Split(':');
if (e.KeyCode == Keys.Enter)
{
for(int i=1;i<words.Length;i++)
{
if (string.compare(words[i],textBox1.text)==0)
{
COMBOX.Items.Add(ConsoleEnter.Text);
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
else
{
COMBOX.Items.Add("Invalid Command");
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
}
}
}
try this ..
use namespace using System.Net;

Related

program shifts data to the right by 1

My code below appends a period to the end of a character entered but each time it shifts the data by 1 extra space to the right. How would I get back that space? The program is very space sensitive
private void button1_Click(object sender, EventArgs e)
{
string stringToReplace = textBox1.Text;
if (stringToReplace.Length == 0)
{
MessageBox.Show("Please enter a valid string.");
return;
}
if (stringToReplace.Length != 6)
{
MessageBox.Show("Please enter a valid string that is 6 characters in length.");
return;
}
OpenFileDialog filedialog = new OpenFileDialog();
DialogResult result = filedialog.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string filePath = filedialog.FileName;
try
{
int counter = 0;
List<string> lines = new List<string>();
System.IO.StreamReader file = new System.IO.StreamReader(filePath);
string line;
while ((line = file.ReadLine()) != null)
{
if (counter == 0 && !line.Contains(stringToReplace+ "."))
{
line = line.Replace(stringToReplace, stringToReplace + ".");
}
counter++;
lines.Add(line);
}
file.Close();
string ext = Path.GetExtension(filePath);
string newFilename = filePath.Replace(ext, "-new" + ext);
System.IO.File.WriteAllLines(newFilename, lines.ToArray());
MessageBox.Show("Process is completed.");
}
catch (IOException)
{
MessageBox.Show("We apologize but an error occured can you try again?");
}
}
}
This screenshot shows how the file should look after the program executes:
The below screenshot shows how it looks how the initial program executes:
As you can see it shifted by one.

How to send CheckedListBox selection into textfile?

I'm trying to code on my own for the first time, and decided to make a music player on Winforms.
I have a CheckedListBox that is already populated with the names of songs in a folder.
When I click a button, it's supposed to send the names of my selected songs into a .txt file for further manipulation, before closing the form.
For simplification, I'm just going with 1 selected song first.
private void selectbtn_Click(object sender, EventArgs e)
{
selectedSongs = checkedListBox1.CheckedItems.ToString();
songRecord.writeRecord(selectedSongs); //i initialised my streamreader/streamwriter class and called it songRecord
this.Close();
}
in my streamreader/writer class, this is what I have
class DataRecord
{
public void writeRecord(string line)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(#"C:\Users\Me\Desktop\JAM_MACHINE\record.txt", true);
sw.WriteLine(line);
}
catch (FileNotFoundException)
{
Console.WriteLine("Error: File not found.");
}
catch (IOException)
{
Console.WriteLine("Error: IO");
}
catch(Exception)
{
throw;
}
finally
{
if (sw != null)
sw.Close();
}
}
public void readRecord()
{
StreamReader sr = null;
string myInputline;
try
{
sr = new StreamReader(#"C:\Users\Me\Desktop\JAM_MACHINE\record.txt");
while ((myInputline = sr.ReadLine()) != null) ; //readline reads whole line
Console.WriteLine(myInputline);
}
catch (FileNotFoundException)
{
Console.WriteLine("Error: File not found");
}
catch(IOException)
{
Console.WriteLine("Error: IO");
}
catch (Exception)
{
throw;
}
finally
{
if (sr != null)
sr.Close();
}
}
}
When I run it, the .txt file doesn't show my selection. It only shows:
System.Windows.Forms.CheckedListBox+CheckedItemCollection
What went wrong?
Iterate through the CheckedItems Collection and collect each item inside a string array. I assume you fill the checkedListBox with strings
private void selectbtn_Click(object sender, EventArgs e)
{
string[] checkedtitles = new string[checkedListBox1.CheckedItems.Count];
for (int ii = 0; ii < checkedListBox1.CheckedItems.Count; ii++)
{
checkedtitles[ii] = checkedListBox1.CheckedItems[ii].ToString();
}
string selectedSongs = String.Join(Environment.NewLine, checkedtitles);
songRecord.writeRecord(selectedSongs);
this.Close();
}

How to load paths into ListBox and afterwards start the file per selected Index

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void cmdAdd_Click(object sender, EventArgs e)
{
OpenFileDialog OP = new OpenFileDialog();
OP.Title = "Please select the wanted .exe";
string FileName = String.Empty;
string PathName = String.Empty;
OP.InitialDirectory = #"C:\Users\" + Environment.UserName.ToString() + #"\Desktop";
OP.DefaultExt = ".exe";
OP.Filter = "Game executable (*.exe) |*.exe";
DialogResult Ergebnis = OP.ShowDialog();
if (Ergebnis == DialogResult.OK)
{
FileInfo File = new FileInfo(OP.FileName);
if (File.Exists)
{
PathName = File.FullName;
}
}
if (PathName != String.Empty)
{
textBox1.Text = PathName;
listBox1.Items.Add(PathName);
}
}
private void cmdStart_Click(object sender, EventArgs e)
{
string SelectedItem = "";
if (listBox1.SelectedItem != null)
{
SelectedItem = listBox1.SelectedItem.ToString();
/*MessageBox.Show(SelectedItem);*/
}
Process Pro = new Process();
Pro.StartInfo.FileName = SelectedItem;
DialogResult Ergebnis2 = MessageBox.Show("Would you like to start the Game right now?", "Game start?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (Ergebnis2.Equals(true))
{
try
{
Pro.Start();
}
catch (Exception)
{
MessageBox.Show("The Start of the Program was aborted!\r\nOr you didn't specify the right Path!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
private void cmdSave_Click(object sender, EventArgs e)
{
StreamWriter SaveFile = new StreamWriter(#"C:\Users\" + Environment.UserName.ToString() + #"\Desktop\savedgames.txt");
foreach (var item in listBox1.Items)
{
SaveFile.WriteLine(item.ToString());
}
SaveFile.Close();
MessageBox.Show("EZPZ");
}
private void cmdLoad_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(#"C:\Users\" + Environment.UserName.ToString() + #"\Desktop\savedgames.txt");
string line = string.Empty;
try
{
line = sr.ReadLine();
while (line != null)
{
this.listBox1.Items.Add(line);
line = sr.ReadLine();
}
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
sr.Close();
}
}
}
Hello Stackoverflow-Community,
So i've tried to be able to start the selected File(from the Listbox) by clicking the Start button.The items in the Listbox are loaded in from a .txt-File, But it seems that the path that i get (from the .txt-File) is not actually the same that was written inside.
For example: H:\Exe\556689600.exe is written inside the .txt-File but when i check while pausing the application the value of the SelectedItem is "H:(two backslashes)Exe(two backslashes)556689600.exe" so i'd like it to be H:\Exe\556689600.exe so it can be properly started.
EDIT: The main problem is that i can't start the .exe that i selected (via cmdStart) and i don't know why.
Please keep in mind that i'm (as you can see from the code) not very experienced in programming and that i'm not an native english speaker, so pardon me for any grammatical mistakes/logic mistakes made.
Thanks in advance,
Stephen
The problem is with:
DialogResult Ergebnis2 = MessageBox.Show("Would you like to start the Game right now?", "Game start?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (Ergebnis2.Equals(true))
DialogResult holds the Enum data 'DialogResult.Yes', so you need to compare it to that value, and not (true).
Edit:
I suggest practicing working with debug:
In this case, I plated a breakpoint on the 'cmdstart_Click' method and followed it step by step (Used F10)
I saw that we jump over the 'if' condition, and checked why.

Reading from a text file using C#

So I'm making a chat program but I am having issues creating a new line in the text box instead of overwriting the other message. Here is my code:
private void refreshRate_Tick(object sender, EventArgs e)
{
String ChatPath = #"Path";
String line;
try
{
StreamReader sr = new StreamReader(#"Path");
line = sr.ReadLine();
richTextBox1.Text = null;
while (line != null)
{
richTextBox1.AppendText(Environment.NewLine);
richTextBox1.Text = line;
line = sr.ReadLine();
}
sr.Close();
}
catch (Exception r)
{
Console.WriteLine("Exception: " + r.Message);
}
finally
{
}
}
You don't need StreamReader or Environment.NewLine
richTextBox1.Text=File.ReadAllText(path);
I think you want to remove the line
richTextBox1.Text = line;
and add
richTextBox1.AppendText(line);
after you've read it from the file.
If you change
richTextBox1.Text = line to richTextBox1.AppendText(line); you'll lose the last line so change the while block as:
while (line != null)
{
richTextBox1.AppendText(Environment.NewLine);
line = sr.ReadLine();
richTextBox1.AppendText(line??"");
}

working with StreamReader and text files

I want to put a test loop on the button click event. When I click this button, it reads the contents of the text file, but I want it to pop up an error message showing “unable to read file”, if it’s not a text file....
This is my code
private void button3_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(textBox1.Text);
richTextBox1.Text = sr.ReadToEnd();
sr.Close();
}
How can I go about it?
A few if-statements and the namespace System.IO will do it
string filename = textBox1.Text;
if (Path.GetExtension(filename).ToLower()) == ".txt") {
if (File.Exists(filename)) {
// Process the file here
} else {
MessageBox.Show("The file does not exist");
}
} else {
MessageBox.Show("Not a text file");
}
Not the best code, but it should work. Ideally you would separate the logic into two methods, a function to check the file exists and is a text file (returning a bool), another to read the contents if the check function returned true and populate the textbox with the contents.
EDIT: This is better:
private void button3_Click(object sender, EventArgs e)
{
string filePath = textBox1.Text;
bool FileValid = ValidateFile(filePath);
if (!IsFileValid)
{
MessageBox.Show(string.Format("File {0} does not exist or is not a text file", filePath));
}
else
{
textbox2.Text = GetFileContents(filePath);
}
}
private bool IsFileValid(string filePath)
{
bool IsValid = true;
if (!File.Exists(filePath))
{
IsValid = false;
}
else if (Path.GetExtension(filePath).ToLower() != ".txt")
{
IsValid = false;
}
return IsValid;
}
private string GetFileContents(string filePath)
{
string fileContent = string.Empty;
using (StreamReader reader = new StreamReader(filePath))
{
fileContent = reader.ReadToEnd();
}
return fileContent;
}

Categories

Resources