繁体   English   中英

尝试将嵌套的字符串列表导出到文本或csv文件C#

[英]Trying to export a nested list of strings to a text or csv file c#

我正在尝试将嵌套列表中的字符串导出到用户选择的txt或csv文件中,并且似乎一切正常,但是当我在导出文件后实际去检查文件时,该文件绝对是空白的。 我去了一个单独的测试程序并模拟了我的问题,它可以在该程序上运行,但是当我将代码移到它上面时,仍然不会导出任何内容。

这只是我初始化的嵌套列表(如果需要)。

List<List<string>> aQuestion = new List<List<string>>();

这是代码的问题区域。

static void writeCSV(List<List<string>> aQuestion, List<char> aAnswer)
    {
        StreamWriter fOut = null;
        string fileName = "";

        //export questions
        //determine if the file can be found
        try
        {
            Console.Write("Enter the file path for where you would like to export the exam to: ");
            fileName = Console.ReadLine();
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException();
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("File {0} cannot be found", fileName);
        }

        //writes to the file
        try
        {
            fOut = new StreamWriter(fileName, false);
            //accesses the nested lists
            foreach (var line in aQuestion)
            {
                foreach (var value in line)
                {
                    fOut.WriteLine(string.Join("\n", value));
                }
            }
            Console.WriteLine("File {0} successfully written", fileName);
        }
        catch (IOException ioe)
        {
            Console.WriteLine("File {0} cannot be written {1}", fileName, ioe.Message);
        }

因此,如果你们中的任何一个可以帮助我解决这个问题,那将是很好的,因为这似乎是一个很小的问题,但我无法终生解决。

可能未将缓冲区刷新到磁盘。 您应该处置流编写器,它将所有内容推送到磁盘:

using (StreamWriter writer = new StreamWriter(fileName, false)) // <-- this is the change
{
    //accesses the nested lists
    foreach (var line in aQuestion)
    {
        foreach (var value in line)
        {
            writer.WriteLine(string.Join("\n", value));
        }
    }
}

从更详细的角度讲,通常会缓冲可能导致性能下降的流。 文件流绝对是经过缓冲的,因为将每个单独的数据立即推送到IO效率非常低。

使用文件流时,可以使用StreamWriter.Flush()方法显式刷新其内容-如果要调试代码并希望查看写入数据的距离,该方法很有用。

但是,通常您不会自己冲洗流,而只是让其内部机制选择最佳时机来执行此操作。 相反,您必须确保布置流对象,这将在关闭流之前强制刷新缓冲区。

改用这种简单的方法,它会容易得多,并且将负责创建和处置StreamWriter。

File.WriteAllLines(PathToYourFile,aQuestion.SelectMany(x=>x));

有关File.WriteAllLines更多参考,请File.WriteAllLines 此处

另外,在您的代码中,您不会处置StreamWrite。 将其包含在“ Using块中。 像这样..

using(var writer = new StreamWriter(PathToYourFile,false)
{
   //Your code here
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM