c# - Trying to populate textbox and listview from txt file - c#

I'm only able to load the textbox and can't seem to get the listview to populate. But, after I remove this.textBox1.Text = sr.ReadToEnd(); listview has populated. Here's code:
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
string line = String.Empty;
this.textBox1.Text = sr.ReadToEnd(); // remove it, listview working
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(new char[0]);
ListViewItem item = new ListViewItem
{
Text = data[0]
};
item.SubItems.Add(data[1]);
listView1.Items.Add(item);
}
}
Screenshots:
Img1
Img2

Well, sr.ReadToEnd() reads the file upto its end, and that's why ReadLine() is of no use.
Let's read the file line by line and update text (which we'll assign to this.textBox1.Text) and listView1.Items:
StringBuilder text = new StringBuilder();
bool firstLine = true;
// We don't want redrawing after each ListViewItem adding
listView1.BeginUpdate();
try {
// File.ReadLines is easier to manipulate with StreamReader
// if you want just read lines
foreach (string line in File.ReadLines(openFileDialog1.FileName)) {
if (!firstLine)
sb.AppendLine();
sb.Append(line);
firstLine = false;
// 3: We want at most 3 chunks (item, subitem and tail to throw away)
string[] data = line.Split(new char[0], 3);
ListViewItem item = new ListViewItem() {
Text = data[0]
};
if (data.Length > 1)
item.SubItems.Add(data[1]);
listView1.Items.Add(item);
}
}
finally {
// The file has been scanned, items added; now we a ready to redraw the listView1
listView1.EndUpdate();
}
this.textBox1.Text = text.ToString();

You can use the following.
ReadToEnd does this: Reads all characters from the current position to the end of the stream. You are losing the position of the stream.
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
string line = String.Empty;
StringBuilder sb = new StringBuilder();
// this.textBox1.Text = sr.ReadToEnd(); // remove it, listview working
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(new char[0]);
ListViewItem item = new ListViewItem
{
Text = data[0]
};
item.SubItems.Add(data[1]);
listView1.Items.Add(item);
sb.AppendLine(line);
}
this.textBox1.Text = sb.ToString();
}

You can try this:
string filename = openFileDialog1.FileName;
var lines = File.ReadAllLines(filename);
textBox1.Text = string.Join(Environment.NewLine, lines);
foreach ( string line in lines )
{
var items = line.Split(new char[0]);
if ( items.Length > 0 )
{
var item = new ListViewItem(items[0]);
if ( items.Length > 1 )
item.SubItems.Add(items[1]);
listView1.Items.Add(item);
}
}

Related

use streamreader find the specific user entry in the text file and display the 5th component in label

Data was passed from another form which containing a user entry, using Streamreader find the specific user entry in the text file and display the 5th component in the array.
in the login form, I passed the user entry: seow into this form, how do I make sure it displays 20, in label3?
in account.txt
seow 1111 wen 12345 20 50
user 1234 user1 12345 70 80
C# Code:
List<string> user = new List<string>();
private void Balance_Load(object sender, EventArgs e)
{
string username;
username = login.accountname;
StreamReader sr = new StreamReader("account.txt");
string line = "";
if (user.Contains(username))
{
while ((line = sr.ReadLine()) != null)
{
string[] components = line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
label3.Text = string.Join(" ", components[5]);
}
sr.Close();
}
}
here is an example of I have tried
string path1 = AppDomainAppPath + "\\Subscribtion\\Subscribe.txt";
System.IO.StreamReader file = new System.IO.StreamReader(path1);
var lines = File.ReadAllLines(path1);
for (var i = 0; i < lines.Length; i += 1)
{
// Process line
txtcollege.Value = lines[1];
txtplace.Value = lines[3];
}
file.Close();
ouput
ive madeit by changing the condition, thanks for the ideas
while ((line = sr.ReadLine()) != null)
{
string[] components = line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if( components.Contains(username))
{
curbal = string.Join(" ", components[5]);
label3.Text = curbal;
savbal = string.Join(" ", components[6]);
label5.Text = savbal;
}
}
sr.Close();

How do I delete all lines in text file below certain text?

I have a code which iterates through the entire text file searching for a specific text "[names]", and "tried" to delete all the lines below the text. I tried File.WriteAllText(INILoc, string.Empty);, but this just deletes everything in the entire text file. How do I make it so only all the lines below "[names]" gets deleted?
I have set up the iteration likes this :
string[] lines = File.ReadAllLines(INILoc);
bool containsSearchResul = false;
foreach (string line in lines)
{
if (containsSearchResul)
{
File.WriteAllText(INILoc, string.Empty);
}
if (line.Contains("[names]"))
{
containsSearchResul = true;
}
}
You need to store lines before "[names]" text into a string variable, and when condition (line.Contains("[names]")) satisfy then just break the loop and write string value into the same file.
Something like,
string[] lines = File.ReadAllLines(INILoc); //Considering INILoc is a string variable which contains file path.
StringBuilder newText = new StringBuilder();
bool containsSearchResul = false;
foreach (string line in lines)
{
newText.Append(line);
newText.Append(Environment.NewLine); //This will add \n after each line so all lines will be well formatted
//Adding line into newText before if condition check will add "name" into file
if (line.Contains("[names]"))
break;
}
File.WriteAllText(INILoc, newText.ToString());
//^^^^^^^ due to string.Empty it was storing empty string into file.
Note: If you are using StringBuilder class, then do not miss to add Using System.Text in your program
Use StreamReader as it will give you the best performance as you don't need to read the whole file. Swap 'PATH TO INPUT FILE' with your file path and the result will be stored at the path you provide for 'PATH TO OUTPUT FILE'.
using (var sr = new StreamReader("PATH TO INPUT FILE"))
{
using (var sw = new StreamWriter("PATH TO OUTPUT FILE"))
{
var line = sr.ReadLine();
while (line != null)
{
sw.WriteLine(line);
if (line.Contains("[names]"))
{
sw.Close();
sr.Close();
}
else
{
line = sr.ReadLine();
}
}
}
}
If you need to write to the same file:
var sb = new StringBuilder();
using (var sr = new StreamReader("PATH TO INPUT FILE"))
{
var line = sr.ReadLine();
while (line != null)
{
sb.AppendLine(line);
if (line.Contains("[names]"))
{
sr.Close();
}
else
{
line = sr.ReadLine();
}
}
}
File.WriteAllText("PATH TO INPUT FILE", sb.ToString());
Based on the requested code I have put together modifications.
string[] lines = File.ReadAllLines(INILoc);
//create a list to hold the lines
List<string> output = new List<string>();
//loop through each line
foreach (string line in lines)
{
//add current line to ouput.
output.Add(line);
//check to see if our line includes the searched text;
if (line.Contains("[names]"))
{
//output to the file and then exit loop causing all lines below this
//one to be skipped
File.WriteAllText(INILoc, output.ToArray());
break;
}
}
The problem with your code is that it delete all the lines before the [names], not after (more exactly, write only the lines after that text). Also, any time you rewrite all the file content, and so remove all previous wrote line. It'll work as follows:
string[] lines = File.ReadAllLines(INILoc);
using (StreamWriter writer = new StreamWriter(INILoc)) // https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file
{
bool containsSearchResul = false;
foreach (string line in lines)
{
if (!containsSearchResul)
{
writer.Write(INILoc, string.Empty);
}
if (line.Contains("[names]"))
{
containsSearchResul = true;
}
}
}
You have another, better option to do this with break:
string[] lines = File.ReadAllLines(INILoc);
using (StreamWriter writer = new StreamWriter(INILoc)) // https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file
{
foreach (string line in lines)
{
if (line.Contains("[names]"))
{
break;
}
writer.WriteLine(INILoc, string.Empty);
}
}
But you can do this in prefered, more-readable way, by using LINQ:
using System.Linq;
// ...
string[] lines = File.ReadAllLines(INILoc);
string[] linesTillNames = lines
.Take( // Take just N items from the array
Array.IndexOf(lines, "[names]") // Until the index of [names]
)
.ToArray();
File.WriteAllLines(INILoc, linesTillNames);
You can also use: WriteAllLines(string path, IEnumerable<string> contents) like this:
string[] lines = File.ReadAllLines(INILoc);
List<string> linesToWrite = new List<string>();
foreach(string line in lines)
{
linesToWrite.Add(line);
if (line.Contains("[names]")) break;
}
File.WriteAllLines(INILoc, linesToWrite);

Csharp substring text and add it to list

I have file.txt like:
EDIT: I didn't wrote but this is important i guess- In file.txt there can be others lines!
folder=c:\user;c:\test;c:\something;
I need to add one path like one list item (List<string> Folders).
So my List should looks like:
Folders[0] = c:\user
Folders[1] = c:\test
etc. (without text "folder=" which starts line in file.txt and ";" which means end of path).
file can contain much more paths.
I did something like this:
using (FileStream fss = new FileStream(path, FileMode.Open))
{
using (StreamReader sr = new StreamReader(fss))
{
while (sr.EndOfStream == false)
{
string line = sr.ReadLine();
if(line.StartsWith("folders"))
{
int index = line.IndexOf("=");
int index1 = line.IndexOf(";");
string folder = line.Substring(index + 1, index1 - (index + 1));
Folders.Add(folder);
Now in List Folders i have first path but what now? I can't go ahead :(
using(var sr = new StreamReader(path))
{
var folders = sr.ReadToEnd()
.Split(new char[]{';','\n','\r'}, StringSplitOptions.RemoveEmptyEntries)
.Select(o => o.Replace("folder=",""))
.ToArray();
Folders.AddRange(folders);
}
You can try following code, using File.ReadAllText
string Filepath = "c:\abc.txt";
string filecontent = File.ReadAllText(Filepath);
string startingString = "=";
var startIndex = filecontent.IndexOf(startingString);
filecontent = filecontent.Substring(startIndex + 1, filecontent.Length - startIndex - 2);
List<String> folders = filecontent.Split(';').ToList();
Here's a simple example:
List<String> Folders = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\Users\mikes\Documents\SomeFile.txt";
string folderTag = "folder=";
using (FileStream fss = new FileStream(path, FileMode.Open))
{
using (StreamReader sr = new StreamReader(fss))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
if (line.StartsWith(folderTag))
{
line = line.Substring(folderTag.Length); // remove the folderTag from the beginning
Folders.AddRange(line.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
}
}
}
}
foreach(string folder in Folders)
{
Console.WriteLine(folder);
}
}
I'd use this approach if you're going to read line by line, and do something else based on what each line starts with. In that case you could add different else if(...) blocks:
if (line.StartsWith(folderTag))
{
line = line.Substring(folderTag.Length); // remove the folderTag from the beginning
Folders.AddRange(line.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
}
else if(line.StartsWith("parameters="))
{
// do something different with a line starting with "parameters="
}
else if (line.StartsWith("unicorns="))
{
// do something else different with a line starting with "unicorns="
}

Read text file from resource

I am trying the following code to split the words in a text file.
The file is written like this:
Apple"Juice"Martini
Lemon"Juice"Party
Banana"Smoothie"Aligns
and the code following:
string resource_data = Properties.Resources.textfile;
string[] result = resource_data.Split('"');
foreach (string lines in result)
{
if(comboBox1.Text == result[0])
{
richTextBox2.Text = result[2];
}
}
Taken & edited from a c++ program I was working on which worked perfectly with the same txt file.
String^ resource_data = "textfile.txt";
try
{
StreamReader^ DataIn = File::OpenText(resource_data);
String^ DataStr;
int count = 0;
array<String^>^ result;
array<Char>^ separ = gcnew array<Char>{'"'};
while((DataStr = DataIn->ReadLine()) != nullptr)
{
count++;
result = DataStr->Split(separ);
if(comboBox1->Text == result[0]) // result[0] = Name
{
What the code does..
Read each line as it own.
Gives first word in each line result[0] as second word on each line is result[1] etc.
When I select a word in the combobox I check if it is the same as in the text file and that line is used in result[x].
But in the C# it gives ALL words own result[x] and lines does not matter.
How can I make the following code in c++ to work in C# but having the text file in the resources.resx?
I think I see what the problem is. You first need to split the string resource_data into separate lines. You could do this by splitting resource_data on the new line character(s):
string[] lines = resource_data.Split(new string[1] { Environment.NewLine }, StringSplitOptions.None);
foreach (var line in lines)
{
string[] parts = line.Split('"');
if (comboBox1.Text == result[0])
{
richTextBox2.Text = result[2];
}
}
You could also do this using a StringReader:
using (StringReader reader = new StringReader(resource_data))
{
while (reader.Peek() >= 0)
{
string[] parts = reader.ReadLine().Split('"');
if (comboBox1.Text == result[0])
{
richTextBox2.Text = result[2];
}
}
}
Additionally if you are only storing the path to the file in the resources, you could open the file and read from it:
using (StreamReader reader = File.OpenText(resource_path)) // path to file
{
while (reader.Peek() >= 0)
{
string[] parts = reader.ReadLine().Split('"');
if (comboBox1.Text == result[0])
{
richTextBox2.Text = result[2];
}
}
}

Read text file and split it over

So, I know my headline is a bit confusing, I will explain.
My code looks like this:
string filename = "C:\\C#\\maplist.txt"; // please put the text file path.
string filename2 = "C:\\C#\\zemaplist.txt";
string map;
StreamReader sr = new StreamReader(filename);
StreamWriter sw = new StreamWriter(filename2);
List<string> maps = new List<string> { };
while ((map = sr.ReadLine()) != null)
{
maps.Add(map);
}
sr.Close();
for (int i = 0; i < maps.Count; i++)
{
Console.WriteLine(maps[i]);
sw.WriteLine(maps[i]);
}
sw.Close();
and what i need to do is when the code read a new line, in my line there is
"Hey,Hey"
I want to split the , from each other so I can take both of them as other parameters, so that the first Hey will be added to maps and the other hey will be maps2,
How can I do that?
You can use Split() function to Split the given String based on delimiter.
Try This:
while ((map = sr.ReadLine()) != null)
{
maps.Add(map.Split(',')[0].Trim());
maps2.Add(map.Split(',')[1].Trim());
}
Simple Code:
using System.IO;
string filename = "C:\\C#\\maplist.txt"; // please put the text file path.
string filename2 = "C:\\C#\\zemaplist.txt";
string map;
StreamWriter sw = new StreamWriter(filename2);
List<string> maps = new List<string> { };
List<string> maps2 = new List<string> { };
String [] allLines = File.ReadAllLines(filename);
foreach(String line in allLines)
{
maps.Add(line.Split(',')[0].Trim());
maps2.Add(line.Split(',')[1].Trim());
}
for (int i = 0; i < maps.Count; i++)
{
Console.WriteLine(maps[i]);
sw.WriteLine(maps[i]);
}
sw.Close();
Solution 2:
String mapItem1="";
String mapItem2="";
if(maps.Count == maps2.Count)
{
for(int i=0;i<maps.Count;i++)
{
mapItem1=maps[i];
mapItem2=maps2[i];
}
}
while ((map = sr.ReadLine()) != null)
{
string[] split = map.Split(',');
//First Hey would be split[0], second Hey would be split[1]
maps.Add(split[0].Trim());
maps2.Add(split[1].Trim());
}
The Split method should help you out with that.
If you want to trim leading whitespace characters, you can use the .Trim() method on a string.
Use Split().
string heys = "Hey,Hey";
string[] splitArray = heys.Split(',');
Then you have:
splitArray[0] = "Hey";
splitArray[1] = "Hey";
Why even bother reading line by line? Read the entire file, replace the new line chars for a "," (to prevent last and first elements from different lines to be treated as one), and loop through a clean string.
string fileContent = Regex.Replace(File.ReadAllText("test.txt"), #"\r", ",");
List<string> mapList = new List<string>();
foreach (string map in Regex.Split(fileContent.Replace(#"\s+", ""), ","))
{
mapList.Add(map.Trim());
}

Categories

Resources