views:

72

answers:

2

Hello,

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.

+3  A: 

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) {...}
Marc Gravell
+1  A: 

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);
    }
}
Jeeva S