尝试将嵌套的字符串列表导出到文本或 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 Here

此外,在您的代码中您没有处理 StreamWrite。将其包含在 Using 块中。像这样..

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