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

C#中整数数组垂直写入文本文件及读取至控制台的问题

问题排查与正确实现方案

错误原因

你的代码里每次循环调用File.WriteAllText("new.txt", inttostr),这个方法的特性是每次执行都会覆盖目标文件的全部现有内容。循环迭代4次,前3次写入的内容都会被下一次覆盖,最终文件里只会保留最后一次写入的元素4。

正确实现方案

这里提供三种常用的正确写法,按需选择:

方案1:使用File.AppendAllText追加写入

通过追加的方式逐行写入元素,避免覆盖:

public static void Main()
{
    int[] numArray = new int[] {1,2,3,4};
    // 先清空文件,避免残留旧内容
    File.WriteAllText("new.txt", string.Empty);
    
    foreach (int num in numArray)
    {
        // 追加元素并添加换行符,保证每行一个元素
        File.AppendAllText("new.txt", num.ToString() + Environment.NewLine);
    }

    // 读取并逐行输出
    using (StreamReader sr = new StreamReader("new.txt"))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }
    }
}

方案2:一次性写入所有内容(性能更优)

先将数组转换为每行一个元素的字符串,再一次性写入文件,减少IO操作次数:

public static void Main()
{
    int[] numArray = new int[] {1,2,3,4};
    // 用换行符连接所有数组元素,生成完整文本内容
    string fileContent = string.Join(Environment.NewLine, numArray);
    File.WriteAllText("new.txt", fileContent);

    // 直接读取所有行并输出
    foreach (string line in File.ReadAllLines("new.txt"))
    {
        Console.WriteLine(line);
    }
}

方案3:使用StreamWriter逐行写入

借助StreamWriter的WriteLine方法自动添加换行符,同时using块会自动管理流资源:

public static void Main()
{
    int[] numArray = new int[] {1,2,3,4};
    
    using (StreamWriter sw = new StreamWriter("new.txt"))
    {
        foreach (int num in numArray)
        {
            sw.WriteLine(num);
        }
    }

    // 读取全部内容并输出
    using (StreamReader sr = new StreamReader("new.txt"))
    {
        string allContent = sr.ReadToEnd();
        Console.WriteLine(allContent);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:10:46