开发者

Invalid Argument When Using String Array

I'm building a program that uses a WriteAllLines generic function:

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

But the problem is that when I use开发者_开发技巧 it like this:

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

I know why this problem happens, it's because value is a string and I'm putting it in a place of a string array(string[]), but how I can change my code to solve this? Thanks.


Two options; params, or just new[] {value}

Meaning:

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

or

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

or (C# 2.0)

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

Note that all do exactly the same thing in terms of creating arrays etc. The final option is to create a more-specific overload:

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


why dont you WriteAllText method in File Class..

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜