使用C#StreamWriter

时间:2018-03-15 16:20:32

标签: c# file streamwriter

我正在练习使用c#

写入文件

我的代码无效(未在文件中写入)

{
    int T, N; //T = testCase , N = number of dice in any Test
    int index = 0, straight;
    List<string> nDiceFaceValues = new List<string>(); //List for Dice Faces
    string line = null;  //string to read line from file
    string[] lineValues = {};  //array of string to split string line values

    string InputFilePath = @ "E:\Visual Studio 2017\CodeJam_Dice Straight\A-small-practice.in"; //path of input file
    string OuputFilePath = @
    "E:\Visual Studio 2017\CodeJam_Dice Straight\A-small-practice.out"; //path of otput file

    StreamReader InputFile = new StreamReader(InputFilePath);
    StreamWriter Outputfile = new StreamWriter(OuputFilePath);

    T = Int32.Parse(InputFile.ReadLine());  //test cases input
    Console.WriteLine("Test Cases : {0}", T);

    while (index < T) {
        N = Int32.Parse(InputFile.ReadLine());
        for (int i = 0; i < N; i++) {
            line = InputFile.ReadLine();
            lineValues = line.Split(' ');

            foreach(string j in lineValues)
            {
                nDiceFaceValues.Add(j);
            }
        }
        straight = ArrangeDiceINStraight(nDiceFaceValues);
        Console.WriteLine("case:  {0} , {1}", ++index, straight);

        Outputfile.WriteLine("case:  {0} , {1}", index, straight);
        nDiceFaceValues.Clear();
    }
}

这段代码有什么问题?

我是如何解决的?

为什么它不起作用?

注意:我想逐行写入文件

1 个答案:

答案 0 :(得分:0)

缺少的原因是:关闭内容 - 刷新缓冲区等:

private static bool IsComplexObject(Type type, bool recurse = true)
{
    if (type.IsArray) return 
    (
        recurse
        ? IsComplexObject(type.GetElementType(), false) 
        : false
    );
    //etc.

但是,如果您要为每一行执行此操作,using(var outputfile = new StreamWriter(ouputFilePath)) { outputfile.WriteLine("case: {0} , {1}", index, straight); } 可能会更方便。

请注意,默认情况下File.AppendText覆盖,因此您还需要考虑到这一点:

new StreamWriter

此处的using(var outputfile = new StreamWriter(ouputFilePathm, true)) { outputfile.WriteLine("case: {0} , {1}", index, straight); } 适用于true

如果您打开了一个用于并发读/写的文件,您还可以尝试添加append,但是......它不能保证做任何事情。< / p>