2015-05-14 58 views
-8

非常简单直接,我想从文件中读取;将字符串值转换为int,迭代使用“”作为语句“并将该文件写入另一个文件。写入时,应将每个数字写入新行。我想使用File类的WriteAllLines静态方法。它只接受一个字符串数组,我怎么做到这一点?我的代码片段是这样的:使用C#对文件进行读取和写入#

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文件。

+1

那么您可以将每个**数字**添加到'string []',然后将'string []'发送到'File.WriteAllLines'方法。 –

+0

坚持......你懂Parse方法吗? –

+1

@PawelMaga如果仅仅是关于'Parse'方法... – Luaan

回答

1

问题是你正在循环内声明你的字符串数组,并且从不用任何东西填充它。相反,将该字符串数组移到循环外部。另外,我不认为每次都要通过循环写入文件,所以也要将文件写入循环之外。

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); 
} 
+0

Chris Dunaway,单词不能很好地表达我很欣赏你的贡献。你解决了这个问题。 – kehinde

0

你可以这样做:

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验证。