Read text file, split it, then show it in listBox - c#

I need to read a text file containing time stamps and temperatures. The thing is, I need to only show the temperatures in a listBox, spliting the string before displaying it.
So far I've managed to show the text file in the list, but im struggling with removing the timestamps.
My code:
public partial class Form1 : Form
{
OpenFileDialog openFile = new OpenFileDialog();
string line = "";
private void button1_Click(object sender, EventArgs e)
{
if (openFile.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFile.FileName);
while(line != null)
{
line = sr.ReadLine();
if(line != null)
{
string[] newLine = line.Split(' ');
listBox1.Items.Add(newLine);
}
}
sr.Close();
}
}
Now the listBox only shows String[] array.
Oh, and also I need to include this in my code:
const int numOfTemp = 50;
double dailyTemp[numOfTemps];
The textfile is in this format:
11:11:11 -10,50

You should take [1] item of the the array after Split:
using System.Linq;
...
private void button1_Click(object sender, EventArgs e)
{
if (openFile.ShowDialog() != DialogResult.OK)
return;
var temps = File
.ReadLines(openFile.FileName)
.Select(line => line.Split(' ')[1]); // we need temperature only
try {
listBox1.BeginUpdate();
// In case you want to clear previous items
// listBox1.Items.Clear();
foreach (string temp in temps)
listBox1.Items.Add(temp);
}
finally {
listBox1.EndUpdate();
}
}

Related

C# Rewrite textfile when listview is using textfile

I've tried and tried but I can't figure out how I'm supposed to fix this.
I have a listView that reads data from a text file.
private void Form3_Load(object sender, EventArgs e)
{
listView1.View = View.Details;
listView1.FullRowSelect = true;
listView1.Columns.Add("Modell", 200);
listView1.Columns.Add("Kw", 100);
listView1.CheckBoxes = true;
string RD_Paneler = "./Data/Paneler.txt";
try
{
List<string> data = File.ReadAllLines(RD_Paneler).ToList();
foreach (string d in data)
{
string[] items = d.Split(new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries);
listView1.Items.Add(new ListViewItem(items));
}
}
catch
{
}
}
`
So then I wanted the user to be able to press a "DELETE" button and all the checkboxed items would be deleted.
private void button2_Click(object sender, EventArgs e)
{
string exeFolder = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string settingFile = exeFolder + "/Data/Paneler.txt";
var tempFile = Path.GetTempFileName();
string alltext = File.ReadAllText(settingFile);
foreach (ListViewItem item in listView1.Items)
{
var linesToKeep = File.ReadLines(settingFile).Where(l => l != item.Checked.ToString());
if (item.Checked)
{
listView1.Items.Remove(item);
File.WriteAllLines(tempFile, linesToKeep);
File.Delete(settingFile); //Here is where to program crash happends.
File.Move(tempFile, settingFile);
}
}
}
The problem now is that when the program tries to delete the file and replace it with the new one the program crashes because the file it tries to delete is already in use because of the listview.
Here's few solutions -
Use File.ReadAllLines() instead of File.ReadLines(). This should solve the primary problem you are having.
Since you have already read the settingsFile once in memory into alltext. Just use that to iterate over lines like alltext.Split('\n'). Even better IMO.
Hard to understand what your code is doing. Seems sketchy that in a for loop, you have set it up to write, delete, and move the same two files over and again?

My program is duplicating the input stream from a textbox C#

So, I am a newbie in C# and I have this listbox in my program that is duplicating the contents that it's reading from a textbox.
Whenever I start my program, it loads the contents of the save.txt file to the listbox, but when it does that, it loads a duplicate of all the save.txt content. I tried clearing the listbox before loading the contents but it's not working.
Here's my code:
private void readList()
{
string line;
listBox.Items.Clear(); //I tried to clear the listbox but it's not working
listBox.Items.AddRange(File.ReadAllLines(#"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"));
using (StreamReader sr = new StreamReader("save.txt"))
while ((line = sr.ReadLine()) != null)
{
listBox.Items.Add(line);
}
}
public myAgenda()
{
InitializeComponent();
readList();
}
private void add_btn_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(add_txt.Text))
{
MessageBox.Show("Error: Please enter a value");
}
else
{
holder = add_txt.Text;
listBox.Items.Add(ctr + " " + holder);
ctr++;
add_txt.Text = " ";
}
}
private void button1_Click(object sender, EventArgs e)
{
const string sPath = "save.txt";
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
foreach (var item in listBox.Items)
{
SaveFile.WriteLine(item);
}
SaveFile.Close();
Application.Exit();
}
You are filling listbox two time in readlist method i.e.
First Time :
listBox.Items.AddRange(File.ReadAllLines(#"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"));
Second Time :
using (StreamReader sr = new StreamReader("save.txt"))
while ((line = sr.ReadLine()) != null)
{
listBox.Items.Add(line);
}
You can remove either of one approach to fill up the content. First approach is better to use for readability.
You are copying the content twice on your listBox.
Try to do this:
private void readList()
{
string line;
listBox.Items.Clear();
//Comment out this line then put the File Directory on the StreamReader
//listBox.Items.AddRange(File.ReadAllLines(#"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"));
using (StreamReader sr = new StreamReader(#"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"))
while ((line = sr.ReadLine()) != null)
{
listBox.Items.Add(line);
}
}

How can I save a list to a file then read the items back into a ListBox?

I am attempting to save a simple list to a file without using Serialize. Is this possible?
public partial class Form1 : Form
{
public List<string> _testList = new List<string>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int _add = 0;
string _addString ="";
for (int i = 0; i < 5; i++)
{
_add =+ i;
_addString = Convert.ToString(_add);
_testList.Add(_addString);
}
TextWriter tw = new StreamWriter("SavedList.txt", true);
foreach (string s in _testList)
tw.WriteLine(s);
tw.Close();
StreamReader streamReader = new StreamReader("SavedList.txt");
// Read the data to the end of the stream.
listBox1.Text = streamReader.ReadToEnd();
// Close the text stream reader.
streamReader.Close();
// Close the file stream.
//fileStream.Close();
}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
}
This emits no errors, however it does nothing.
I will use Serialize if necessary, however the suspicion is that is not necessary. Is it?
You can use the File Class to facilitate this.
File.WriteAllLines("SavedList.txt", _testList.ToArray());
To read it back you can then use:
string[] lines = File.ReadAllLines("SavedList.txt");
foreach (string line in lines)
listBox1.Items.Add(line);
your problem is that the Text field of ListBox
doesn't work like that.
change:
listBox1.Text = streamReader.ReadToEnd();
to:
foreach(string s in streamReader.ReadToEnd().Split(new string[]{"\r\n"}))//!!!the end of line characters may differ depending on your system!!!
{
listBox1.Items.Add(s);
}
the Text field holds the currently selected text . it is not for adding items to the list.

Getting extra lines, but I don't know why

I am making a WPF program, and right now I want to be able to open and merge files. I have a button to open a file and I have a button to merge the file, and when I don't implement the "onTextChanged" method both buttons work properly and the files are formatted properly. But if I implement the onTextChanged method and use the merge file button, the previous 'file' gets extra lines in its output.
Open Button Code:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
//Open windows explorer to find file
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = true;
if (ofd.ShowDialog() ?? false)
{
//clears the buffer to open new file
buffer.Clear();
//string to hold line from file
string text;
// Read the file and add it line by line to buffer.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((text = file.ReadLine()) != null)
{
buffer.Add(text);
}
//close the open file
file.Close();
//write each element of buffer as a line in a temporary file
File.WriteAllLines("temp", buffer);
//open that temporary file
myEdit.Load("temp");
}
}
Merge Button Code:
private void merge_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = true;
if (ofd.ShowDialog() ?? false)
{
string text;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((text = file.ReadLine()) != null)
{
buffer.Add(text); // myEdit.AppendText(text);
}
file.Close();
File.WriteAllLines("temp", buffer);
myEdit.Load("temp");
}
}
And when I execute this code, it adds lines in between the last 'file's output:
private void myEdit_TextChanged(object sender, EventArgs e)
{
tCheck.Stop();
tCheck.Start();
}
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
tCheck.Stop();
Application.Current.Dispatcher.Invoke(new Action(() =>
{
buffer.Clear();
StringBuilder sb = new StringBuilder();
// pulls text from textbox
string bigS = myEdit.Text;
// getText();
for (int i = 0; i < (bigS.Length - 1); i++)
{
if (bigS[i] != '\r' && bigS[i + 1] != '\n')
{
sb.Append(bigS[i]);
}
else
{
buffer.Add(sb.ToString());
sb.Clear();
}
}
}));
}
If you are wondering why I don't use the Split method of a string, it is because I need to open 50+ MB text files and I get an out of memory exception upon using it. I really just want to keep formatting the same when I merge a file.
Wow this is a one line fix.
Original Line of Code:
buffer.Add(sb.ToString());
Changed (Correct) Line of Code:
buffer.Add(sb.ToString().Trim());
The changed worked, however if someone has any idea where these extra lines are coming from that would be helpful.

to display doc file in text format asp.net c#

i want to read content of file.but these code is not helping.
string[] readText = File.ReadAllLines(path); this line is giving error.
protected void btnRead_Click(object sender, EventArgs e)
{
string path = fileupload1.PostedFile.FileName;
if (!string.IsNullOrEmpty(path))
{
string[] readText = File.ReadAllLines(path);
StringBuilder strbuild = new StringBuilder();
foreach (string s in readText)
{
strbuild.Append(s);
strbuild.AppendLine();
}
textBoxContents.Text = strbuild.ToString();
}
}
The File.ReadAllText function expects the file to exist on the specified location. You haven't saved it on the server and yet you are attempting to read it. If you don't need to save the uploaded file on the server you could read directly from the input stream.
protected void btnRead_Click(object sender, EventArgs e)
{
if (fileupload1.PostedFile != null && fileupload1.PostedFile.ContentLength > 0)
{
using (var reader = new StreamReader(fileupload1.PostedFile.InputStream))
{
textBoxContents.Text = reader.ReadToEnd();
}
}
}
This will work for text files. If you want to parse some other formats such as Word documents you will need a library to do that.
this should work
string[] lines = System.IO.File.ReadAllLines(#"..\asd.txt");
for (i = 0; i < lines.Count; i++)
System.Console.WriteLine("Contents = " + lines[i]);
}

Categories