2009-11-12 59 views
0

我建立一个使用WriteAllLines通用功能的程序:无效参数当使用字符串数组

private static void WriteAllLines(string file, string[] contents) 
{ 
    using (StreamWriter writer = new StreamWriter(file)) 
    { 
     foreach (string line in contents) 
     { 
      writer.Write(line); 
     } 
    } 
} 

但问题是,当我使用它是这样的:

string temp = Path.GetTempFileName(); 
string file = ReadAllText(inputFile); 
WriteAllLines(temp, value); 

我知道为什么会出现这个问题,这是因为value是一个字符串,我把它放在一个字符串数组(string[])的地方,但我怎么能改变我的代码来解决这个问题?谢谢。

+0

这有什么错File.WriteAllLines? http://msdn.microsoft.com/en-us/library/system.io.file.writealllines.aspx – 2009-11-12 17:56:27

+0

不,它是另一个通用函数。 ;) – 2009-11-12 17:58:06

回答

3

两个选项; params,或者只是new[] {value}

含义:

WriteAllLines(string file, params string[] contents) {...} 

WriteAllLines(temp, new[] {value}); 

或(C#2.0)

WriteAllLines(temp, new string[] {value}); 

注意,所有在创造方面做同样的事情数组等。最后的选项是创建一个更具体的过载:

WriteAllLines(string file, string contents) {...} 
1

你为什么不WriteAllText方法在文件类..

using System; 
using System.IO; 
using System.Text; 

class Test 
{ 
    public static void Main() 
    { 
     string path = @"c:\temp\MyTest.txt"; 

     // This text is added only once to the file. 
     if (!File.Exists(path)) 
     { 
      // Create a file to write to. 
      string createText = "Hello and Welcome" + Environment.NewLine; 
      File.WriteAllText(path, createText); 
     } 

     // This text is always added, making the file longer over time 
     // if it is not deleted. 
     string appendText = "This is extra text" + Environment.NewLine; 
     File.AppendAllText(path, appendText); 

     // Open the file to read from. 
     string readText = File.ReadAllText(path); 
     Console.WriteLine(readText); 
    } 
} 
相关问题