You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 遍历指定目录txt文件时输出System.String[]而非文件名如何处理

问题原因

你直接将string[]类型的files数组传入Console.WriteLine()时,方法会默认调用数组的ToString()方法,而C#中数组的ToString()默认实现仅返回自身的类型名称System.String[],不会自动遍历输出数组内存储的每一个文件名。

解决方法

有两种常用的修复方案:

  • 方案1:遍历数组逐个输出每个匹配到的文件名
    对应修改后的代码如下:
Console.WriteLine("What is the path?");
string path = Console.ReadLine();
string[] files = System.IO.Directory.GetFiles(path,"*.txt");
// 遍历数组逐个输出
foreach (var file in files)
{
    Console.WriteLine(file);
}
  • 方案2:将数组所有元素拼接为单个字符串后一次性输出
    可以用string.Join()方法将所有文件名用分隔符(比如换行符)拼接后再打印,代码如下:
Console.WriteLine("What is the path?");
string path = Console.ReadLine();
string[] files = System.IO.Directory.GetFiles(path,"*.txt");
// 用换行符拼接所有文件名后输出
Console.WriteLine(string.Join(Environment.NewLine, files));

内容的提问来源于stack exchange,提问作者Techy Shadow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 04:48:03