2009-11-12 57 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); 
    } 
} 
相關問題