简体   繁体   English

如何将 txt 中的所有项目添加到列表框中?

[英]How do I add all items from txt to a listbox?

So basically I need a button that will add all text from txt file, that already exists in the folder of bin/debug.所以基本上我需要一个按钮来添加 txt 文件中的所有文本,这些文本已经存在于 bin/debug 文件夹中。 I was trying to come up with something but it didn't go that well我试图想出一些东西,但它没有 go

const string sPath = "save.txt";

        System.IO.StreamReader ReadFile = new System.IO.StreamReader(sPath);
        if (File.Exists(sPath))
        {
            string str = File.ReadAllText(sPath);
            foreach (char item in sPath)             
            { 
                ListBoxOutput.Items.Add(str);

            }             
        }

        ReadFile.Close();

        MessageBox.Show("Information loaded");

Upd: Thanks for the help, I ended up with this: Upd:感谢您的帮助,我最终得到了这个:

 const string sPath = "save.txt";

        System.IO.StreamReader ReadFile = new System.IO.StreamReader(sPath);
        if (File.Exists(sPath))
        {
            string[] lines = File.ReadAllLines(sPath);

            foreach (string item in lines)
            {
                ListBoxOutput.Items.Add(item);

            }
        }

        ReadFile.Close();

        MessageBox.Show("Information loaded!");

change改变

string str = File.ReadAllText(sPath);
foreach (char item in sPath)             
{ 
    ListBoxOutput.Items.Add(str);// there you add all your file content N times where N - count of characters in save file path
}  

to

string[] str = File.ReadAllLines(sPath);
foreach (string item in str)             
{ 
    ListBoxOutput.Items.Add(item);
}  

it is not to clear what you are trying to achieve, but hope this helps这不是要清楚您要达到的目标,但希望这会有所帮助

Try changing尝试改变

string str = File.ReadAllText(sPath);
    foreach (char item in sPath)             
    { 
        ListBoxOutput.Items.Add(str);
    }  

To this对此

IEnumerable<string> str = File.ReadLines(sPath);
foreach (string item in str)             
{ 
    ListBoxOutput.Items.Add(item);
}  

I think that's what you need.我认为这就是你所需要的。 By the way if you have a small file you can use顺便说一句,如果你有一个小文件,你可以使用

File.ReadAllLines(sPath)

Hope this helps.希望这可以帮助。

Instead of adding items one by one to the ListBox, just assign the string array returned by File.ReadAllLines to the ListBox' DataSource property.无需将项目一一添加到 ListBox,只需将File.ReadAllLines返回的字符串数组分配给 ListBox 的DataSource属性。

ListBoxOutput.DataSource = File.ReadAllLines(sPath);

Note: There is no point in opening the StreamReader , since you are not using it.注意:打开StreamReader没有意义,因为您没有使用它。 The entire code:整个代码:

const string sPath = "save.txt";

if (File.Exists(sPath)) {
    ListBoxOutput.DataSource = File.ReadAllLines(sPath);
    MessageBox.Show("Information loaded");
}  else {
    MessageBox.Show("File doesn't exist.");
}

See also: File.ReadAllLines Method另请参阅: File.ReadAllLines 方法

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

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