.net MemoryStream、StreamWriter、FileStream组合在组合时会导致特殊字符

.net MemoryStream、StreamWriter、FileStream组合在组合时会导致特殊字符,.net,csv,memorystream,.net,Csv,Memorystream,嗨,我有下面的代码,我已经减少了从一个更大的任务,我正在工作。基本上,虽然我发现当将内存流组合在一起时,我在连接位置上得到了一个特殊的字符。下面是应用程序完整运行的代码,显示了问题。在Visual Studio代码中打开生成的export.csv文件会在第3行的开头显示一个特殊字符。如果在excel中打开CSV,您会注意到第三行的开头与其他行的外观不同 using System; using System.IO; using System.Text; namespace testingMemo

嗨,我有下面的代码,我已经减少了从一个更大的任务,我正在工作。基本上,虽然我发现当将内存流组合在一起时,我在连接位置上得到了一个特殊的字符。下面是应用程序完整运行的代码,显示了问题。在Visual Studio代码中打开生成的export.csv文件会在第3行的开头显示一个特殊字符。如果在excel中打开CSV,您会注意到第三行的开头与其他行的外观不同

using System;
using System.IO;
using System.Text;

namespace testingMemory
{
    class Program
    {
        static void Main(string[] args)
        {
            var stream1 = GetMemoryStream("section1");
            var stream2 = GetMemoryStream("section2");

            var fileStream = new FileStream("export.csv", FileMode.Truncate, FileAccess.Write);

            stream1.WriteTo(fileStream);
            stream2.WriteTo(fileStream);
        }

        public static MemoryStream GetMemoryStream(string section)
        {
            var wrapper = "\"";

            var memoryStream = new MemoryStream();

            var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8);

            streamWriter.WriteLine($"{wrapper}{section}{wrapper},{wrapper}1{wrapper}");
            streamWriter.Flush();

            streamWriter.WriteLine($"{wrapper}{section}{wrapper},{wrapper}2{wrapper}");
            streamWriter.Flush();

            return memoryStream;
        }
    }
}

每个流都包含一个。当您复制这两个文件时,从第一个流中的字节顺序标记被用作文件的BOM,而第二个则只是中间的垃圾。内存流不应包含BOM表:

using System;
using System.IO;
using System.Text;

namespace testingMemory
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var stream1 = GetMemoryStream("section1"))
            using (var stream2 = GetMemoryStream("section2"))
            {
                using (var fileStream = new FileStream("d:\\export.csv", FileMode.Truncate, FileAccess.Write))
                {
                    stream1.WriteTo(fileStream);
                    stream2.WriteTo(fileStream);
                }
            }
        }

        public static MemoryStream GetMemoryStream(string section)
        {
            var wrapper = "\"";

            var memoryStream = new MemoryStream();

            // Using a non-default UTF-8 encoding with BOM not used: 
            var streamWriter = new StreamWriter(memoryStream, new UTF8Encoding(false));

            streamWriter.WriteLine($"{wrapper}{section}{wrapper},{wrapper}1{wrapper}");
            streamWriter.Flush();

            streamWriter.WriteLine($"{wrapper}{section}{wrapper},{wrapper}2{wrapper}");
            streamWriter.Flush();

            return memoryStream;
        }
    }
}