我正在构建一个使用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 :(得分: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 :(得分:1)
为什么不在File Class中使用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);
}
}