在C#中如何将文本文件中的单词逐行添加到ArrayList中
问题原因
你当前的代码使用File.ReadAllText()方法读取文件,该方法会将整个文本文件的全部内容合并为单个字符串返回,你调用一次wordList.Add(readpath)只会把整个文件内容作为1个元素插入ArrayList,自然无法实现逐行添加单词的需求。
解决方案
你可以使用File.ReadAllLines()方法,该方法会自动按换行符拆分文件内容,返回每行内容组成的字符串数组,直接批量插入ArrayList即可:
using System; using System.Collections; using System.IO; // 业务代码 string path = @"C:\Users\.......\xxx.txt"; // 按行读取文件所有内容 string[] wordLines = File.ReadAllLines(path); ArrayList wordList = new ArrayList(); // 批量添加所有行到ArrayList wordList.AddRange(wordLines);
如果你需要对每行内容做校验(比如跳过空行、过滤特殊字符),可以遍历数组逐行添加:
using System; using System.Collections; using System.IO; string path = @"C:\Users\.......\xxx.txt"; string[] wordLines = File.ReadAllLines(path); ArrayList wordList = new ArrayList(); foreach (string line in wordLines) { // 示例:跳过空白行再添加 if (!string.IsNullOrWhiteSpace(line)) { wordList.Add(line); } }
可选优化建议
C# 中更推荐使用泛型集合List<string>替代非泛型的ArrayList,不需要做类型转换、运行效率更高、类型安全更有保障,示例代码如下:
using System.Collections.Generic; using System.IO; string path = @"C:\Users\.......\xxx.txt"; List<string> wordList = new List<string>(File.ReadAllLines(path));
如果读取文件出现乱码,可以手动指定文件编码,比如读取UTF-8编码的文件修改为:File.ReadAllLines(path, System.Text.Encoding.UTF8)
内容的提问来源于stack exchange,提问作者ozgurburakbulut
相关产品推荐
相关产品推荐

