I was wondering how i can make the program read a text file and put the contents in the listbox using streamreader?
private void button1_Click(object sender, EventArgs e)
{
} (StreamReader stRead = new StreamReader("C:\Users\tommy\Desktop\WindowsFormsApplication9\WindowsFormsApplication9\bin\Debug\transactions.txt"))
{
while (!stRead.EndOfStream)
{
ListBox1.Items.Add(stRead.ReadLine());
}
Using File.ReadAllLines
Be aware of the # at the beginning of the file path. Using backslash in a string literal must be escaped if # not used.
ListBox1.Items.AddRange(File.ReadAllLines(#"C:\Users\tommy\Desktop\WindowsFormsApplication9\WindowsFormsApplication9\bin\Debug\transactions.txt"));
Using StreamReader:
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
ListBox1.Items.Add(line);
}
}
An much easier way is to use File.ReadAllLines
string[] lines = File.ReadAllLines("yourFile");
foreach(string line in lines)
{
ListBox1.Items.Add(line);
}
using File.ReadAllLines also,
string[] lines = File.ReadAllLines( #"yourFile" );
lines.ForEach( x => Listbox1.Items.Add( x ) );
Related
I know this has been asked a few times, but I have seen a lot of regex etc., and I'm sure there is another way to do this with just a stream reader/writer. Below is my code. I'm trying to replace "tea" with the word "cabbage". Can somebody help? I believe I have the wrong syntax.
namespace Week_9_Exer_4
{
class TextImportEdit
{
public void EditorialControl()
{
string fileName;
string lineReadFromFile;
Console.WriteLine("");
// Ask for the name of the file to be read
Console.Write("Which file do you wish to read? ");
fileName = Console.ReadLine();
Console.WriteLine("");
// Open the file for reading
StreamReader fileReader = new StreamReader("C:\\Users\\Greg\\Desktop\\Programming Files\\story.txt");
// Read the lines from the file and display them
// until a null is returned (indicating end of file)
lineReadFromFile = fileReader.ReadLine();
Console.WriteLine("Please enter the word you wish to edit out: ");
string editWord = Console.ReadLine();
while (lineReadFromFile != null)
{
Console.WriteLine(lineReadFromFile);
lineReadFromFile = fileReader.ReadLine();
}
String text = File.ReadAllText("C:\\Users\\Greg\\Desktop\\Programming Files\\story.txt");
fileReader.Close();
StreamWriter fileWriter = new StreamWriter("C:\\Users\\Greg\\Desktop\\Programming Files\\story.txt", false);
string newText = text.Replace("tea", "cabbage");
fileWriter.WriteLine(newText);
fileWriter.Close();
}
}
}
If you don't care about memory usage:
string fileName = #"C:\Users\Greg\Desktop\Programming Files\story.txt";
File.WriteAllText(fileName, File.ReadAllText(fileName).Replace("tea", "cabbage"));
If you have a multi-line file that doesn't randomly split words at the end of the line, you could modify one line at a time in a more memory-friendly way:
// Open a stream for the source file
using (var sourceFile = File.OpenText(fileName))
{
// Create a temporary file path where we can write modify lines
string tempFile = Path.Combine(Path.GetDirectoryName(fileName), "story-temp.txt");
// Open a stream for the temporary file
using (var tempFileStream = new StreamWriter(tempFile))
{
string line;
// read lines while the file has them
while ((line = sourceFile.ReadLine()) != null)
{
// Do the word replacement
line = line.Replace("tea", "cabbage");
// Write the modified line to the new file
tempFileStream.WriteLine(line);
}
}
}
// Replace the original file with the temporary one
File.Replace("story-temp.txt", "story.txt", null);
In the end i used this : Hope it can help out others
public List<string> EditorialResponse(string fileName, string searchString, string replacementString)
{
List<string> list = new List<string>();
using (StreamReader reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
line = line.Replace(searchString, replacementString);
list.Add(line);
Console.WriteLine(line);
}
reader.Close();
}
return list;
}
}
class Program
{
static void Main(string[] args)
{
TextImportEdit tie = new TextImportEdit();
List<string> ls = tie.EditorialResponse(#"C:\Users\Tom\Documents\Visual Studio 2013\story.txt", "tea", "cockrel");
StreamWriter writer = new StreamWriter(#"C:\Users\Tom\Documents\Visual Studio 2013\story12.txt");
foreach (string line in ls)
{
writer.WriteLine(line);
}
writer.Close();
}
}
}
I need some help with loading text file into a listView. Text file looks like this:
1,6 sec,5 sec,1 sec,17,
2,6 sec,4 sec,2 sec,33,
3,7 sec,5 sec,3 sec,44,
I have to load this into a listView control and every subitem should be separated by comma (or any other character). I tried something like this:
using (var sr = new StreamReader(file))
{
string fileLine = sr.ReadLine();
foreach (string piece in fileLine.Split(','))
{
listView1.Items.Add(piece);
}
sr.Close();
}
it would work just fine apart from only first line is loaded to the first column in listview. I cannot figure it out.
Thanks for your time!
KR!
You have to advance to the next line, you can use a while-loop:
using (var sr = new StreamReader(file))
{
string fileLine;
while ((fileLine = sr.ReadLine()) != null)
{
foreach (string piece in fileLine.Split(','))
{
listView1.Items.Add(piece);
}
}
}
Note that you don't need to close the stream manually, that is done by the using-statement.
Another way is using File.ReadLines or File.ReadAllLines which can help to simplify your code:
var allPieces = File.ReadLines(file).SelectMany(line => line.Split(','));
foreach(string piece in allPieces)
listView1.Items.Add(piece);
using (var sr = new StreamReader(file))
{
while(!sr.EndOfStream)
{
string fileLine = sr.ReadLine();
foreach (string piece in fileLine.Split(','))
{
listView1.Items.Add(piece);
}
sr.Close();
}
}
Ι guess you just have to add:
while (!sr.EndOfStream)
{
string fileLine = sr.ReadLine();
foreach (string piece in fileLine.Split(','))
{
listView1.Items.Add(piece);
}
}
sr.Close();// close put the end of while scope beacause you have a multiline text this code can't be read second line, and throw exceptions this code.
i want to remove stop words from my text file and i write the following code for this purpose
TextWriter tw = new StreamWriter("D:\\output.txt");
private void button1_Click(object sender, EventArgs e)
{
StreamReader reader = new StreamReader("D:\\input1.txt");
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(' ');
string[] stopWord = new string[] { "is", "are", "am","could","will" };
foreach (string word in stopWord)
{
line = line.Replace(word, "");
tw.Write("+"+line);
}
tw.Write("\r\n");
}
but it doesn't show the result in the output file and the output file remain empty.
A regular expression might be perfect for the job:
Regex replacer = new Regex("\b(?:is|are|am|could|will)\b");
using (TextWriter writer = new StreamWriter("C:\\output.txt"))
{
using (StreamReader reader = new StreamReader("C:\\input.txt"))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
replacer.Replace(line, "");
writer.WriteLine(line);
}
}
writer.Flush();
}
This method will only replace the words with blanks and do nothing with the stopwords if they are part of another word.
Good luck with your quest.
The following works as expected for me. However, it's not a good approach because it will remove the stop words even when they are part of a larger word. Also, it doesn't clean up extra spaces between removed words.
string[] stopWord = new string[] { "is", "are", "am","could","will" };
TextWriter writer = new StreamWriter("C:\\output.txt");
StreamReader reader = new StreamReader("C:\\input.txt");
string line;
while ((line = reader.ReadLine()) != null)
{
foreach (string word in stopWord)
{
line = line.Replace(word, "");
}
writer.WriteLine(line);
}
reader.Close();
writer.Close();
Also, I recommend using using statements for when you create your streams in order to ensure the files are closed in a timely manner.
You should wrap your IO objects in using statements so that they are disposed properly.
using (TextWriter tw = new TextWrite("D:\\output.txt"))
{
using (StreamReader reader = new StreamReader("D:\\input1.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(' ');
string[] stopWord = new string[] { "is", "are", "am","could","will" };
foreach (string word in stopWord)
{
line = line.Replace(word, "");
tw.Write("+"+line);
}
}
}
}
Try wrapping StreamWriter and StreamReader in using() {} clauses.
using (TextWriter tw = new StreamWriter(#"D:\output.txt")
{
...
}
You may also want to call tw.Flush() at the very end.
I want to read a .txt file in c# and filter a line out of the string and only show that line. If the match is on the first line, i get a good output using streamreader.ReadLine. But if it's on the second line, i need to get it filtered. (i tought by creating a ReadLine loop?)
Thanks in advance
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(textBox1.Text);
string BoxLM1 = sr.ReadLine();
if (comboBox3.Text == "Anderlecht")
{
if (BoxLM1.Contains("Anderlecht"))
{
label5.Text = BoxLM1;
}
else
{
string BoxLM2 = sr.ReadToEnd();
MessageBox.Show(BoxLM2);
}
You can check all lines at once using File.ReadLines() method and LINQ:
var firstAnderlecht = File.ReadLines(textBox1.Text).FirstOrDefault(s => s.Contains("Anderlecht"));
if (firstAnderlecht != null) {
label5.Text = firstAnderlecht;
}
The ReadLines produces an enumerable of lines from the file; the FirstOrDefault method lets you apply a condition to all lines of the file without a loop, and pick the first line where the condition applies.
If you are manipulating big files i recommend to use this iterator:
private static IEnumerable FileIterator(String filePathe)
{
using (StreamReader streamReader = new StreamReader(filePathe))
{
String line;
while ((line = streamReader.ReadLine()) != null)
{
yield return line;
}
yield break;
}
}
it will prevent the loading of full file to RAM
I am having a little trouble with the streamreader.
I am opening emails from the file dialog, and those emails are placed inside a listbox.
each letter in the emails, are on one line, as shown in the picture below.
I want the emails to be on one line, can some one help me, this is giving me a headache.
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofg = new OpenFileDialog();
ofg.Filter = "Text Files|*.txt";
if (ofg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var fileName = ofg.FileName;
StreamReader sr = new StreamReader(File.OpenRead(fileName));
var line = sr.ReadToEnd();
foreach (var l in line)
listBox1.Items.Add(l.ToString());
sr.Dispose();
}
}
var lines = File.ReadAllLines( fileName );
foreach (var l in lines )
{
listBox1.Items.Add( l );
}
assuming that you have
email1#email1.com
email2#email2.com
in your file (this is what I understood from your description).
use this:
string line;
while((line = reader.ReadLine()) != null)
listBox1.Items.Add(line);
Use it as follow:
using (StreamReader sr = new StreamReader(File.OpenRead(fileName)))
{
string line;
while ((line = sr.ReadLine()) != null)
{
listBox1.Items.Add(line.ToString());
}
}
This reads all the lines in the file and adds it to the listbox line by line.
string containl chars, so foreach (var l ...) iterates through chars in line.
You should replace your foreach with
foreach( var email in line.Split(' '))
In case your emails separated with spaces.
Another approach would be File.ReadAllLines, in case emails in your file is on separate lines...
using (StreamReader sr = new StreamReader(File.OpenRead(fileName)))
{
while (sr.Peek() >= 0)
{
listBox1.Items.Add(sr.ReadLine());
}
}
Reference: http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline