C# 如何让 StreamReader 在读取“~”时跳过一行
我必须在 Visual Studio 中使用 C# 为学校制作一个 Windows 窗体项目,但我不懂 C# (或真正的一般编程)。我一直在使用教程,但我被困住了。 我这样做是为了将多种类型的数据(姓名、电话号码等)输入到一个文本文件中,每个数据都用“~”分隔。我的代码当前使用 StreamReader 将文本文件的每一行放入组合框中,但我希望它只放入“~”符号之前写入的数据,当它检测到它时,它应该跳到下一行。抱歉,如果我解释得不好,我不明白我应该使用的任何术语。
我的代码:
private void addSkiTimesPupilCB_SelectedIndexChanged(object sender, EventArgs e)
{
selectedClass = addSkiTimesPupilCB.SelectedItem.ToString();
}
private void addSkiTimes_Load(object sender, EventArgs e)
{
try
{
StreamReader sr = new StreamReader("pupilDetails.txt");
string line = sr.ReadLine();
while (line != null)
{
string[] components = line.Split("~".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
addSkiTimesPupilCB.Items.Add(line);
line = sr.ReadLine();
}
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex.Message);
}
}
文本文件的格式如下:
姓名〜年龄〜电话号码
如果这意味着什么,我必须输入“using System.IO;”在程序的顶部。
I have to make a windows forms project in visual studio with c# for school, but I don't understand c# (or programming in general really). I've been using tutorials but I'm stuck.
I made it so that multiple types of data - name, phone number, etc, are entered into a text file, with each thing being seperated with a "~". My code currently uses StreamReader to put each line of the text file into a combo box, but I want it to only put data written before the "~" symbol, and when it detects it it should skip to the next line. Sorry if I explained this badly, I don't understand any of the terms I should be using.
My Code:
private void addSkiTimesPupilCB_SelectedIndexChanged(object sender, EventArgs e)
{
selectedClass = addSkiTimesPupilCB.SelectedItem.ToString();
}
private void addSkiTimes_Load(object sender, EventArgs e)
{
try
{
StreamReader sr = new StreamReader("pupilDetails.txt");
string line = sr.ReadLine();
while (line != null)
{
string[] components = line.Split("~".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
addSkiTimesPupilCB.Items.Add(line);
line = sr.ReadLine();
}
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex.Message);
}
}
The text file is formatted like this:
name~age~phone number
If it means anything, I had to enter "using System.IO;" at the top of the program.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎是在说您只希望
name~age~number
中的name
出现在组合中我注意到您在
~
上分割了该行code> 但您不使用拆分的结果:如果您在此处放置
components[0]
,那么只会看到名称进入组合You seem to be saying that you want only the
name
fromname~age~number
to appear in the comboI note that you split the line on
~
but you don't use the result of the split:If instead here you put
components[0]
, then that would see just the name going into the combo