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??"");
}
Related
I'm trying to delete a line from a txt file with my program, but the program has the text file open so I can't. What do I do?
private void btnDeleteTransaction_Click(object sender, EventArgs e)
{
string line = null;
string delete = txtDeleteTransId.Text;
using (reader = new StreamReader(txtFilePath.Text))
{
try {
using (writer = new StreamWriter(txtFilePath.Text, true))
{
while ((line = reader.ReadLine()) != null)
{
if (String.Compare(line + "|", delete) == 0)
continue;
writer.WriteLine(line);
}
}
}
catch (Exception ex)
{
txtMessages.Text = "exception deleting transaction: " + ex.Message;
}
}
}
Figured it out below.
I'm dumb and was trying to write from the reader which you can't do. Here is my working code if anyone is as new as me.
private void btnDeleteTransaction_Click(object sender, EventArgs e)
{
List<string> records = new List<string>();
found = false;
using (reader = new StreamReader(txtFilePath.Text))
{
while (!reader.EndOfStream)
{
record = reader.ReadLine();
if (record.StartsWith(txtDeleteTransId.Text + "|"))
{
found = true;
}
else
{
records.Add(record);
}
}
if (!found)
{
txtMessages.Text = "Record ID was not found";
return;
}
}
try
{
using (writer = new StreamWriter(txtFilePath.Text, false))
{
foreach (var item in records)
{
writer.WriteLine(item);
}
}
txtMessages.Text = "Record deleted";
}
catch (Exception ex)
{
txtMessages.Text = "exception deleting record: " + ex.Message;
}
}
```
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.
This is my working code, I have a filewatcher monitoring my log file, when the file updates (it updates a lot) it reads the log and outputs the lines that comply with the regex to a textbox. The problem with it is that it reads the file from the beginning and re-prints the regexed lines again so I get repeated data in the textbox. I also don't know if I have it setup correctly to run the file read from a separate thread so my program don't "freeze" while reading large log files.
private void btnStart_Click(object sender, EventArgs e)
{
if ((Properties.Settings.Default.setting_logfile != "") && (Properties.Settings.Default.setting_logfolder != ""))
{
if (btnStart.Text == "Start Parsing")
{
// change text on button and switch status image
btnStart.Text = "Stop Parsing";
pbStatus.Image = Properties.Resources.online;
new Thread(() => Run()).Start();
}
else
{
btnStart.Text = "Start Parsing";
pbStatus.Image = Properties.Resources.offline;
fsWatcher.EnableRaisingEvents = false;
}
}
else
{
tbOutput.Text = "Please select a log file to parse.";
}
}
private void Run()
{
try
{
fsWatcher.Changed += new FileSystemEventHandler(OnChanged);
fsWatcher.EnableRaisingEvents = true;
}
catch (Exception ex)
{
MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void OnChanged(object source, FileSystemEventArgs e)
{
string line;
Regex pattern = new Regex(#"\[[\w :]+\]\s<SYSTEMWIDE_MESSAGE>:");
Stream stream = File.Open(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader streamReader = new StreamReader(stream);
while ((line = streamReader.ReadLine()) != null)
{
Match match = pattern.Match(line);
if (match.Success)
{
tbOutput.AppendText(line + "\r\n");
}
}
streamReader.Close();
stream.Close();
}
You could remember the last position that you read at and start from there.
Regex pattern = new Regex(#"\[[\w :]+\]\s<SYSTEMWIDE_MESSAGE>:");
long lastPosition = 0;
private void OnChanged(object source, FileSystemEventArgs e)
{
string line;
Stream stream = File.Open(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
stream.Seek(lastPosition, SeekOrigin.Begin);
StreamReader streamReader = new StreamReader(stream);
while ((line = streamReader.ReadLine()) != null)
{
if (pattern.Match(line).Success)
{
tbOutput.AppendText(line + Environment.NewLine);
}
}
lastPosition = stream.Position; // may need to subtract 1!!!
streamReader.Close();
stream.Close();
}
I have a text file with about 5,000 lines and I want to copy its contents to another file, but only the first 38 characters of each line.
I currently have this code:
private void button1_Click(object sender, EventArgs e)
{
string line, line2;
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\test.txt");
while ((line = file.ReadLine()) != null)
{
line2 = line.Substring(0, 38);
using (System.IO.StreamWriter files = new System.IO.StreamWriter(#"C:\test2.txt"))
{
files.WriteLine(line2);
}
}
file.Close();
}
It only copies the last line. :(
because you rewrite your new file in your loop. You should create your new string in the loop (use a stringBuilder for this will be more efficient), but write the new file out of the loop :
string line;
var sb = new StringBuilder();
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\test.txt");
while ((line = file.ReadLine()) != null)
sb.AppendLine(line.Substring(0, Math.Min(38, line.Length)));
file.Close();
using (System.IO.StreamWriter files = new System.IO.StreamWriter(#"C:\test2.txt"))
{
files.WriteLine(sb.ToString());
}
or to do it shorter
var result = File.ReadAllLines(#"c:\test.txt")
.Select(m => m.Substring(0, Math.Min(38, m.Length)));
File.WriteAllLines(#"C:\test2.txt", result);
You need to move the creation of 'file2' before the while loop.
You should also create 'file' in a using:. You won't need to call close for either one then.
private void button1_Click(object sender, EventArgs e)
{
string line;
using (System.IO.StreamReader file = new System.IO.StreamReader(#"c:\test.txt"))
using (System.IO.StreamWriter file2 = new System.IO.StreamWriter(#"C:\test2.txt"))
while ((line = file.ReadLine()) != null)
{
string line2 = line.Substring(0, 38);
file2.WriteLine(line2);
}
}
Your file's .WriteLine overwrites the entire file every time you call it. Therefore, put the entire code in your using block, or add true to the StreamWriter's arguments to tell it to append to the file instead of overwriting.
Option 1:
private void button1_Click(object sender, EventArgs e)
{
string line, line2;
using (System.IO.StreamWriter files = new System.IO.StreamWriter(#"C:\test2.txt"))
{
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\test.txt");
while ((line = file.ReadLine()) != null)
{
line2 = line.Substring(0, 38);
files.WriteLine(line2);
}
file.Close();
}
}
Option 2:
private void button1_Click(object sender, EventArgs e)
{
string line, line2;
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\test.txt");
while ((line = file.ReadLine()) != null)
{
line2 = line.Substring(0, 38);
using (System.IO.StreamWriter files = new System.IO.StreamWriter(#"C:\test2.txt",true))
{
files.WriteLine(line2);
}
}
file.Close();
}
And finally, if you choose to use a StringBuilder, you can use System.IO.File.WriteAllText(#"C:\test2.txt", stringHere); instead of the entire using and StreamWriter block
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;