Im trying to insert items to a listbox from a text file hosted on my webserver. The text file looks like this:
1:game="x":image="y":
2:game="x2":image="y2":
What Im trying to achieve is to separate the strings AND have the textbox to display multiple items like this:
x
x2
The most important part is, if I added a new line such as "3:game="x3":image="y3":" to my webserver textfile, It'd also have to get that added into the listBox automatically, WITHOUT having to modify the code.
This is the way Im retrieving the string:
string RetrieveList;
WebClient con = new WebClient();
RetrieveList = con.DownloadString("webserver.abc/textfile.txt");
gameList.Items.Add(RetrieveList);
Edit: Figured it out with the help of @David.Warwick
string RetrieveList;
WebClient con = new WebClient();
RetrieveList = con.DownloadString("com.com/data.txt");
string[] sLines = RetrieveList.Split('*'); //split on each new line
foreach (string sLine in sLines)
{
string sGameValue = sLine.Split(',')[0];
gameList.Items.Add(sGameValue);
}
I just changed my text file to be separated with ","'s.
CodePudding user response:
I am not familiar with the DownloadString method of WebClient. But I have a solution for you assuming that you can iterate over each line of RetrieveList, sort of like the ReadLine method of StreamReader.
This assumes that your textfile.txt is always perfect.
int iFirstQuoteIndex = sLine.IndexOf("\"") 1;
int iSecondQuoteIndex = sLine.IndexOf( "\"", iFirstQuoteIndex);
string sGameValue = sLine.Substring(iFirstQuoteIndex, iSecondQuoteIndex - iFirstQuoteIndex);
Assume sLine is one line of text from your file, such as 1:game="x":image="y":
It finds the first occurrence of a double quote, then the second occurrence of a double quote. Then the substring method returns the text in between the double quotes.
Does this help you?
Edit:
I am going to assume that RetrieveList looks something like this:
1:game="x":image="y":\r\n
2:game="x2":image="y2":
If I am right, then you would do something like this.
string[] sLines = RetrieveList.Split("\r\n"); //split on each new line
foreach(string sLine in sLines)
{
int iFirstQuoteIndex = sLine.IndexOf("\"") 1;
int iSecondQuoteIndex = sLine.IndexOf( "\"", iFirstQuoteIndex);
string sGameValue = sLine.Substring(iFirstQuoteIndex, iSecondQuoteIndex - iFirstQuoteIndex);
gameList.Items.Add(sGameValue);
}