C#实现从Web服务器文本文件动态读取内容并添加至ListBox
Alright, let's walk through how you solved this problem (with a big shoutout to David.Warwick for the assist!)—this will be super helpful for others trying to pull dynamic list content from a remote text file into a ListBox.
Problem Recap
You wanted to:
- Pull content from a text file hosted on a web server
- Extract just the
gamevalues (like x, x2, x3) and display them as individual entries in a ListBox - Have any new entries added to the text file automatically show up in the ListBox without modifying code
Solution Breakdown
You made two key adjustments to get this working smoothly:
1. Updated Text File Format
You revised the separators in your remote text file to simplify parsing:
- Use
*to split individual entries (replacing the original colon-heavy line structure) - Use
,to separate thegamevalue from other associated data in each entry
Example updated text file content:
x,y* x2,y2* x3,y3
2. Modified C# Implementation
You adjusted your code to split the downloaded content correctly and loop through each entry to extract the game value:
string RetrieveList; WebClient con = new WebClient(); RetrieveList = con.DownloadString("com.com/data.txt"); // Split the full string into individual entries using * string[] sLines = RetrieveList.Split('*'); foreach (string sLine in sLines) { // Extract the first part (game value) before the comma string sGameValue = sLine.Split(',')[0]; gameList.Items.Add(sGameValue); }
How This Works
WebClient.DownloadString()fetches the entire content of the remote text file- Splitting on
*creates an array of all individual game entries - For each entry, splitting on
,and taking the first element grabs exactly the game name you want to display - Adding each game name to
gameList.Itemsensures they appear as separate entries in the ListBox - Any new entries added to the text file (formatted as
newGameName,newImageValue*) will automatically be picked up next time the code runs—no code edits required!
内容的提问来源于stack exchange,提问作者beamed
相关产品推荐
相关产品推荐

