I have this code
private void button1_Click(object sender, EventArgs e)
{
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
string strfilename = openFileDialog1.FileName;
string filetext = File.ReadAllText(strfilename);
richTextBox3.Text = filetext; // reads all text into one text box
}
}
}
I'm struggling on how to get each line of the text file to a different text box or possibly store it in an array, can some one help please!
File.ReadAllText will read all of the text in a file.
string filetext = File.ReadAllText("The file path");
If you want to store each line separately in an array, File.ReadAllLines can do that.
string[] lines = File.ReadAllLines("The file path");
Optionally, you can use the following to return a list of strings. You can then either bind the list of strings directly to the control, or you can iterate through each item in the list and add them that way. See below:
public static List<string> GetLines(string filename)
{
List<string> result = new List<string>(); // A list of strings
// Create a stream reader object to read a text file.
using (StreamReader reader = new StreamReader(filename))
{
string line = string.Empty; // Contains a single line returned by the stream reader object.
// While there are lines in the file, read a line into the line variable.
while ((line = reader.ReadLine()) != null)
{
// If the line is not empty, add it to the list.
if (line != string.Empty)
{
result.Add(line);
}
}
}
return result;
}
Related
I have a text file like this:
0124456, 10000,2
0124434, 10001,1
0126234, 10002,2
It has about 60-70 rows. I would want to add "0124456" , "0124434" and "0126234" to combobox items. I could only do this with richtextbox. It was showing every line until "," line by line but when i saved it it was saving back only the "0124456" , "0124434" and "0126234" line by line and got rid of "10000,2" etc.
My save code looks like this:
SaveFileDialog svf = new SaveFileDialog();
svf.Filter = "Text files (.csv)|*.csv";
svf.Title = "Save file...";
if (svf.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(svf.FileName);
string[] lines = richTextBox1.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
sw.Write(line, Environment.NewLine);
}
richTextBox1.Clear();
sw.Close();
}
//and my open-read code is this:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Text files (.csv)|*.csv";
ofd.Title = "Open a file...";
if (ofd.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(ofd.FileName);
string currentLine;
while ((currentLine = sr.ReadLine()) != null)
{
if (currentLine == null)
{
break;
}
else
{
string[] adat = currentLine.Split(',');
richTextBox1.AppendText(adat[0] + Environment.NewLine);
}
}
sr.Close();
}
So my purpose would be to open csv file and add the first "words" to combobox items and after i edit them i save back only the edited "word".
Thanks in advance!
Hi your issue is with in the opening of file as you are showing only first part in the rich text box and that is what being saved back
richTextBox1.AppendText(adat[0] + Environment.NewLine);
if you want to save all the lines ,you have to show them all.
I am trying to delete a line from a Text File by clicking on the listed string item in a ListView, but i am getting an error.
The method I am using is to Store the TextFile lines in a Line<string> lines variable and Overwrite the TextFile by making the file empty, the storing the Line<string> lines back into the file.
Delete Line Code:
private void lvNotes_ItemSelected(object sender, AdapterView.ItemClickEventArgs e)
{
//Where I want the Line to be deleted!
string toast = "Deleted: " + notesList.GetItemAtPosition(e.Position);
Toast.MakeText(this, toast, ToastLength.Long).Show();
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string filename = Path.Combine(path, "test.txt");
List<string> lines = new List<string>();
using (StreamReader streamReader = new StreamReader(filename))
{
// 3
// Use while != null pattern for loop
string line;
while ((line = streamReader.ReadLine()) != null)
{
// 4
// Insert logic here.
// ...
// "line" is a line in the file. Add it to our List.
lines.Add(line);
}
using (StreamWriter swOvewrite = new StreamWriter(filename))
{
File.WriteAllText(filename, "");
swOvewrite.WriteLine(lines);
swOvewrite.Close();
UpdateList();
}
}
}
The Error I am getting is shown below:
You cannot open a file for reading and simultaneously write to it. What you need to do is to read the contents out firstly, close the reader and then create a writer and write stuff back to the file.
Another option is to write to a totally different temp file and then replace the original file with the temp file.
Or open the file for both reading and writing:
FileStream s2 = new FileStream("path", FileMode.Open, FileAccess.ReadWrite, FileShare.None);
I am trying to write a program for a school project that will read a csv file containing a name on each line and output each name and the number of times it occurrences in a list box. I would prefer for it not to be pre set for a specific name but i guess that would work also. So far i have this but now I'm stuck. The CSV file will have a name on each line and also have a coma after each name. Any help would be great thanks.
This is what I have so far:
string[] csvArray;
string line;
StreamReader reader;
OpenFileDialog openFileDialog = new OpenFileDialog();
//set filter for dialog control
const string FILTER = "CSV Files|*.csv|All Files|*.*";
openFileDialog.Filter = FILTER;
//if user opens file and clicks ok
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//open input file
reader = File.OpenText(openFileDialog.FileName);
//while not end of stream
while (!reader.EndOfStream)
{
//read line from file
line = reader.ReadLine().ToLower();
//split values
csvArray = line.Split(',');
Using Linq we can do the following:
static IEnumerable<Tuple<int,string>> CountOccurences(IEnumerable<string> data)
{
return data.GroupBy(t => t).Select(t => Tuple.Create(t.Count(),t.Key));
}
Test:
var strings = new List<string>();
strings.Add("John");
strings.Add("John");
strings.Add("John");
strings.Add("Peter");
strings.Add("Doe");
strings.Add("Doe");
foreach (var item in CountOccurences(strings)) {
Console.WriteLine (String.Format("{0} = {1}", item.Item2, item.Item1));
}
John = 3
Peter = 1
Doe = 2
To use in your case:
string filePath = "c:\myfile.txt"
foreach (var item in CountOccurences(File.ReadAllLines(filePath).Select(t => t.Split(',').First())))
Console.WriteLine (String.Format("{0} = {1}", item.Item2, item.Item1));
you can use a dictionary, where you can store the occurrence of each Name:
Dictionary<string,int> NameOcur=new Dictionary<string,int>();
...
while (!reader.EndOfStream)
{
//read line from file
line = reader.ReadLine().ToLower();
//split values
csvArray = line.Split(',');
if (NameOcur.ContainsKey(csvArray[0]))
{
///Name exists in Dictionary increase count
NameOcur[csvArray[0]]++;
}
else
{
//Does not exist add with value 1
NameOcur.Add(csvArray[0],1);
}
}
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 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