简体   繁体   English

c#从文件读取到数组并添加到列表框

[英]c# reading from a file into an array and adding to listbox

So this is a part of a university assignment that I am stuck on, I am to create a media player and the code I am currently struggling with should read from a .txt file into an array, and then it should read the track title into a listbox named Lst_genre, my code so far is as follows (I am quite new to the website so let me know if I need to put anything else.) 因此,这是我坚持的大学作业的一部分,我要创建一个媒体播放器,而我目前正在苦苦挣扎的代码应从.txt文件读入数组,然后将曲目标题读入一个名为Lst_genre的列表框,到目前为止,我的代码如下(该网站是我的新手,请告诉我是否需要添加其他内容。)

private void Form1_Load(object sender, EventArgs e)
{
      string[] readFromfile = File.ReadLines("filepathgoeshere").ToArray();
      ListBox listBox1 = new ListBox();
      // add items 
      Lst_Genre.Items.Add(readFromfile);
      // add to controls 
      Controls.Add(listBox1);
}

the format of the text file is as follows 文本文件的格式如下

2
hip hop // i am wanting this to the textbox
eminem- without me.mp3 // both mp3 files should show in Lst_genre
eminem- lose yourself.mp3

The genre name should read into a textbox above also but at the moment I am more concerned with the track names. 流派名称也应读入上方的文本框中,但此刻我更关注曲目名称。 Would be great if anybody could give some input as I am currently at a loss. 如果任何人都可以提供一些意见,那将是很棒的,因为我目前很茫然。

You have to extract data first: 您必须先提取数据:

var readFromFile = File
  .ReadLines("filepathgoeshere")
  .Skip(1)                                                  // Skip title 
  .Select(line => line.Substring(0, line.LastIndexOf(' '))) // get genre (not number) 
  .ToArray();                                               // we want an array

Then add all the items: AddRange : 然后添加所有项目: AddRange

Lst_Genre.Items.AddRange(readFromfile);

Edit 1 : As far as I can see from the comments 编辑1 :据我所见

I have a textbox above my listbox to hold the genre name and the listbox should hold my track names 我的列表 上方有一个文本 框,用于保存流派名称,列表框应包含我的曲目名称

We actually have to provide data for two controls : 实际上,我们必须提供两个控件的数据:

var allLines = File
  .ReadAllLines("filepathgoeshere");

then 然后

// Top Line: genre name
myTextBox.Text = allLines[0]; 

// tracks
Lst_Genre.Items.AddRange(allLines
  .Skip(1)   // Here we skip top line (genre name?)
  .Select(line => line.Substring(0, line.LastIndexOf(' ')))
  .ToArray());

Edit 2 : According to the example provided: 编辑2 :根据提供的示例:

var allLines = File
  .ReadAllLines("filepathgoeshere");

// Genre name is the second line (top one is id which we skip)
myTextBox.Text = allLines[1]; 

// in case you want to clear existing control, not creating a new one. 
Lst_Genre.Items.Clear();

// Tracks
Lst_Genre.Items.AddRange(allLines
  .Skip(2)     // Here we skip tow lines (id and genre name)
  .ToArray());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM