【问题标题】:Invalid Argument When Using String Array使用字符串数组时参数无效
【发布时间】:2010-12-15 23:57:36
【问题描述】:

我正在构建一个使用 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[]),但是我该如何更改我的代码来解决这个问题呢?谢谢。

【问题讨论】:

标签: c# arrays file-io arguments


【解决方案1】:

两个选项; 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) {...}

【讨论】:

    【解决方案2】:

    为什么不在文件类中使用 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多