首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从文件到字符串数组的C#读取

从文件到字符串数组的C#读取
EN

Stack Overflow用户
提问于 2018-07-29 07:27:51
回答 1查看 126关注 0票数 -5

我希望能够从文本文件中读取数字,并将它们存储在字符串数组中,以便在listBox中显示它们。

下面是代码:

代码语言:javascript
复制
string[] filePath = @"C:Site\Project3\Sales.txt";

foreach (string val in filePath)
{
    listBoxValues.Items.Add(val.ToString());
}
EN

回答 1

Stack Overflow用户

发布于 2018-07-29 07:49:12

你可以这样做:

代码语言:javascript
复制
public List<string> ToList(string filePath)
{
    // Identifiers used are:
    var valueList = List<string>();
    var fileStream = new StreamReader(filePath);
    string line;

    // Read the file line by line
    while ((line = fileStream.readLine()) != null)
    {
       // Split the line by the deliminator (the line is a single value)
       valueList.Add(line);
    }
}

或者你也可以尝试这样的更通用的东西:

代码语言:javascript
复制
public List<string> ToList(string filePath, char deliminator=',')
{
    // Identifiers used are:
    var valueList = List<string>();
    var fileStream = new StreamReader(filePath);
    string line;

    // Read the file line by line
    while ((line = fileStream.readLine()) != null)
    {
       // Split the line by the deliminator
       var splitLine = line.Split(deliminator);
       foreach (string value in splitLine) 
       {
          valueList.Add(value);
       }
    }
}

然后,您可以使用此选项填充列表框。这不是最有效的方法,但它应该适用于您的情况,如果需要,您可以在此基础上进行构建。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51576019

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档