I have this being echo into a blank page:
echo "Testing|Testing1|Testing2|Testing3|Testing4<br/>";
echo "Something|Something1|Something2|Something3|Something4";
Now I have a listview. In this example it would create 2 rows with 5 columns. So my question is, how to read line by line to properly create the number of rows that are displayed on the website?
Here's my code so far:
WebClient client = new WebClient();
string downloadString = client.DownloadString("https://example.com/Testing.php");
string[] downloadString2 = downloadString.Split(
new char[]
{
(char)'|'
}, System.StringSplitOptions.RemoveEmptyEntries);
ListViewItem item = new ListViewItem(
new[]
{
downloadString2[0].ToString(),
downloadString2[1].ToString(),
downloadString2[2].ToString(),
downloadString2[3].ToString(),
downloadString2[4].ToString()
});
listView1.Items.Add(item);
(The columns are already created in the listview)
--
Edit: This worked fine for me:
WebClient client = new WebClient();
string downloadString = client.DownloadString("https://example.com/Testing.php");
string[] stringSeparators = new string[] { "<br/>" };
string[] Lines = downloadString.Split(stringSeparators, StringSplitOptions.None);
string[] things = new string[5]; // Fixed size. I might find a way later to make it dynamically
int i = 0;
foreach (string line in Lines)
{
string[] words = line.Split('|');
i = 0;
foreach (string word in words)
{
things[i] = word;
i++;
}
ListViewItem item = new ListViewItem(
new[]
{
things[0],
things[1],
things[2],
things[3],
things[4]
});
listView1.Items.Add(item);
}
not exactly what you want but you can try this
WebClient client = new WebClient();
string downloadString = client.DownloadString("https://example.com/Testing.php");
string[] stringSeparators = new string[] {"<br/>"};
string[] Lines = downloadString.Split(stringSeparators, StringSplitOptions.None);
foreach (string line in Lines)
{
string[] words = line.Split('|');
foreach (string word in words)
{
ListViewItem item = new ListViewItem();
item.add(word);
}
listView1.Items.Add(item);
}
Related
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);
}
}
In this script, I'm trying to read lines of a txt file on my web server and display it to a list box but it is not reading new lines!
public byte[] GetFileViaHttp(string url)
{
using (WebClient client = new WebClient())
{
return client.DownloadData(url);
}
}
private void Form1_Load(object sender, EventArgs e)
{
var result = GetFileViaHttp(#"https://www.lunabooster.com/list/script-list.txt");
string str = Encoding.UTF8.GetString(result);
string[] strArr = str.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < strArr.Length; i++)
{
OpenSourceListBox.Items.Add(strArr[i].ToString());
}
}
I test your code and work fine if you change \r\n to \n .
Change this :
string[] strArr = str.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
To:
//
string[] strArr = str.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
I am trying to get a list of words (below) to be put into an array. I want each word to be in it's own index.
Here is my code that I have so far.
string badWordsFilePath = openFileDialog2.FileName.ToString();
StreamReader sr = new StreamReader(badWordsFilePath);
string line = sr.ReadToEnd();
string[] badWordsLine = line.Split(' ');
int BadWordArrayCount = 0;
foreach (string word in badWordsLine)
{
badWords[BadWordArrayCount] = word;
BadWordArrayCount = BadWordArrayCount + 1;
}
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;
Here is the list of words I want to import.
label
invoice
post
document
postal
calculations
copy
fedex
statement
financial
dhl
usps
8
notification
n
irs
ups
no
delivery
ticket
If someone could give me an example of how to get this to work, that would be a huge help.
Simplified code:
string badWordsFilePath = openFileDialog2.FileName.ToString();
string[] badWords = File.ReadAllLines(badWordsFilePath);
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;
If every word starts on a new line then you do not need to create a for loop. The Split method will convert to an array for you.
string badWordsFilePath = openFileDialog2.FileName.ToString();
StreamReader sr = new StreamReader(badWordsFilePath);
string line = sr.ReadToEnd();
string[] badWords = line.Split('\n');
You are splitting on space, but there is a newline between each word. Split on newline instead:
string[] badWordsLine = line.Split(new string[]{ Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
Then you have to create the array to put the words in:
badWords = new string[badWordsLine.Length];
However, to loop through a string array just to copy the strings to a string array seems pointless. Just assing the string array to the variable. Also, you forgot to close the stream reader, which is best taken care of with a using block:
string badWordsFilePath = openFileDialog2.FileName.ToString();
string line;
using (StreamReader sr = new StreamReader(badWordsFilePath)) {}
line = sr.ReadToEnd();
}
badWords = line.Split(new string[]{ Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;
Maybe try this modification? It allows on splitting on various white spaces.
string badWordsFilePath = openFileDialog2.FileName.ToString();
StreamReader sr = new StreamReader(badWordsFilePath);
string line = sr.ReadToEnd();
string[] badWordsLine = line.Split(new string[] {" ", "\t", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);
int BadWordArrayCount = 0;
foreach (string word in badWordsLine)
{
badWords[BadWordArrayCount] = word;
BadWordArrayCount = BadWordArrayCount + 1;
}
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;
Do you have to use a StreamReader? If you do not have to, then this code is clearer (in my opinion).
string text = File.ReadAllText(badWordsFilePath);
string[] words = Regex.Split(text, #"\s+");
If you're 100% certain that each word is on its own line and there are no empty lines, this might be overkill; and the File.ReadAllLines suggestion by #Ulugbek Umirov is simpler.
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());
}
Adding the items in a checkedListBox:
DirectoryInfo dinfo = new DirectoryInfo(#"D:\\templates");
FileInfo[] Files = dinfo.GetFiles("*.xml");
foreach (FileInfo file in Files)
{
checkedListBox1.Items.Add(file.Name);
}
foreach (string i in checkedListBox1.CheckedItems)
{
string[] array1 = i;
for (int k = 0; k < array1.Length; k++)
{
XmlDocument xdoc1 = new XmlDocument();
xdoc1.Load(array1[k]);
string s1 = array1[k].ToUpper();
int n = s1.IndexOf(array1[k]);
name1 = array1[k].Substring(n);
}
When I'm putting it in an array, with (string[] array1 = i;)
it's an giving error:
Cannot implicitly convert type 'string' to 'string[]' "
any suggestions?
You can not do that. You will need to do something like this
string[] array1 = new string[] { i };
You are trying to assign string to string[]. Which is not allowed.
string[] array1 = new string[]{i};
DirectoryInfo dinfo = new DirectoryInfo(#"D:\\templates");
FileInfo[] Files = dinfo.GetFiles("*.xml");
Array.ForEach(Files, str => checkedListBox1.Items.Add(str.Name));
foreach (string i in checkedListBox1.CheckedItems)
{
XmlDocument xdoc1 = new XmlDocument();
xdoc1.Load(i);
name1 = i.Substring(i.ToUpper().IndexOf(i));
}