【问题标题】:Read, write, from and to a file using C#使用 C# 读取、写入和写入文件
【发布时间】:2015-07-26 02:25:35
【问题描述】:

非常简单直接,我想从文件中读取;将字符串值转换为 int,使用“for 语句”进行迭代并将文件写入另一个文件。写入时,应将每个数字写在新行上。我想使用 File 类的 WriteAllLines 静态方法。它只接受一个字符串数组,我该如何完成?我的代码 sn-p 是这样的:

static void Main(string[] args)
        {
            String Readfiles = File.ReadAllText(@"C:\Users\ken4ward\Desktop\Tidy\WriteLines.txt");
            Int32 myInt = Int32.Parse(Readfiles);

            for (int i = 0; i < myInt; ++i)
            {
                Console.WriteLine(i);
                Console.ReadLine();  
                String[] start = new String[i];
            File.WriteAllLines(@"C:\Users\ken4ward\Desktop\Tidy\writing.txt", start);
            }
        }

这很简单。使用一堆代码,将迭代的输出写入 .txt 文件。迭代只计算方法被调用的次数。这部分完美地完成了。如果该方法被调用 10 次,它只会写入 10。第二个类文件读取该文件并将其写入另一个 .txt 文件。我想要做的是,因为第一个文件只写一个数字。举个例子——10,第二个文件里写的应该是这样的:

1
2
3
4
5
6
7
8
9
10    

意味着它将每个数字写在一个新行上。问题是它没有写入txt文件。

【问题讨论】:

  • 您可以将每个 数字 添加到 string[],然后将 string[] 发送到 File.WriteAllLines 方法。
  • 等等...你了解 Parse 方法吗?
  • @PawelMaga 如果只是关于 Parse 方法...
  • 你需要澄清你到底想要什么... txt 有一个数字吗?你想写什么到文件中?新行上的数字的每个数字?还是从零到特定数字的所有数字?
  • 您知道,如果您从文本中解析每个数字,然后将每个数字写入文件,您将转换回文本?所以输入和输出文件是一样的。

标签: c# arrays string file loops


【解决方案1】:

你可以这样做:

File
    .WriteAllLines(@"C:\Users\ken4ward\Desktop\Tidy\writing.txt",
        File
            .ReadAllLines(@"C:\Users\ken4ward\Desktop\Tidy\WriteLines.txt")
            .Select(x => int.Parse(x))
            .Select(x => x.ToString())
            .ToArray());

但与文件副本相同,但每行都有一个脆弱的int 验证。

【讨论】:

    【解决方案2】:

    问题是你在循环中声明了你的字符串数组,而从来没有用任何东西填充它。而是将该字符串数组移到循环之外。另外,我认为您不想每次都通过循环写入文件,因此也将文件写入移出循环。

    static void Main(string[] args)
    {
        String Readfiles = File.ReadAllText(@"C:\Users\ken4ward\Desktop\Tidy\WriteLines.txt");
        Int32 myInt = Int32.Parse(Readfiles);
    
        //Declare array outside the loop
        String[] start = new String[myInt];
    
        for (int i = 0; i < myInt; ++i)
        {
            //Populate the array with the value (add one so it starts with 1 instead of 0)
            start[i] = (i + 1).ToString();
    
            Console.WriteLine(i);
            Console.ReadLine();  
        }
    
        //Write to the file once the array is populated
        File.WriteAllLines(@"C:\Users\ken4ward\Desktop\Tidy\writing.txt", start);
    }
    

    【讨论】:

    • Chris Dunaway,言语无法很好地表达我对您的贡献的感激之情。你解决了问题。
    猜你喜欢
    • 1970-01-01
    • 2013-03-17
    • 2020-04-16
    • 2014-12-29
    • 1970-01-01
    • 2023-03-06
    • 2012-09-15
    • 2019-01-24
    • 2010-11-11
    相关资源
    最近更新 更多