c# - StreamWriter 中的特殊字符

标签 c# streamwriter

我正在使用 streamwriter 将字符串写入流中。现在,当我访问流中的数据时,它会在内容末尾添加“\0\0\0”字符。我必须附加流内容,所以它会产生问题,因为我无法通过 trim() 或 remove() 或 replace() 方法删除这些字符。

下面是我使用的代码:

用于写作:

using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
    using (StreamWriter writer = new StreamWriter(stream, System.Text.Encoding.Unicode))
    {
        try
        {
            string[] files = System.IO.Directory.GetFiles(folderName, "*.*", System.IO.SearchOption.AllDirectories);
            foreach (string str in files)
            {
                writer.WriteLine(str);
            }
            // writer.WriteLine(folderName);
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Unable to write string. " + ex);
        }
        finally
        {
            mutex.ReleaseMutex();
            mutex.WaitOne();
        }
    }
}

供阅读:

 StringBuilder sb = new StringBuilder();
            string str = @"D:\Other Files\Test_Folder\New Text Document.txt";
 using (var stream = mmf.CreateViewStream())
                {
                    System.IO.StreamReader reader = new System.IO.StreamReader(stream);
                    sb.Append(reader.ReadToEnd());
                    sb.ToString().Trim('\0');
                    sb.Append("\n" + str);
                }

我怎样才能避免这种情况?

[更新] 写作

// Lock
            bool mutexCreated;
            Mutex mutex = new Mutex(true, fileName, out mutexCreated);
            if (!mutexCreated)
                mutex = new Mutex(true);
            try
            {
                using (MemoryMappedViewStream stream = mmf.CreateViewStream())
                {
                    using (BinaryWriter writer = new BinaryWriter(stream))
                    {
                        try
                        {
                            string[] files = System.IO.Directory.GetFiles(folderName, "*.*", System.IO.SearchOption.AllDirectories);
                            foreach (string str in files)
                            {
                                writer.Write(str);
                            }
                            writer.Flush();
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("Unable to write string. " + ex);
                        }
                        finally
                        {
                            mutex.ReleaseMutex();
                            mutex.WaitOne();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Unable to monitor memory file. " + ex);
            }

阅读

StringBuilder sb = new StringBuilder();
            string str = @"D:\Other Files\Test_Folder\New Text Document.txt";
            try
            {
                using (var stream = mmf.CreateViewStream())
                {
                    System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);
                    sb.Append(reader.ReadString());
                    sb.Append("\n" + str);
                }
                using (var stream = mmf.CreateViewStream())
                {
                    System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
                    writer.Write(sb.ToString());
                }
                using (var stream = mmf.CreateViewStream())
                {
                    System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);
                    Console.WriteLine(reader.ReadString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Unable to monitor memory file. " + ex);
            }

最佳答案

没有 '\0' 被 StreamWriter 追加。这些只是内存映射文件的内容,在您开始编写之前就已经存在了。 StreamReader 需要一个文件结束指示器来知道何时停止读取。 mmf 中没有任何超出该部分的大小 的内容。就像您传递给 MemoryMappedFile.CreateNew(string, long) 的第二个参数一样。

或者换句话说,您创建的 mmf 太大而无法容纳流。好吧,当然,你没有时间机器来猜测它有多大。你肯定需要做点什么,修剪零是不够的。第二次你写一个更短的流时就出错了。读者现在仍会看到先前流内容中的字节,并且它们不会为零。

否则这是 mmfs 的一个常见问题,它们只是内存块,而流是对内存块的非常糟糕的抽象。 mmfs 花了这么长时间才得到 .NET 支持的重要原因之一,尽管它们是一个非常核心的操作系统功能。您需要指针来映射 mmf,而这在托管语言中并没有得到很好的支持。

在这种情况下,我看不到教 StreamReader 新技巧的好方法。将字节从 mmf 复制到 MemoryStream 可以解决问题,但会破坏 mmf 的意义。

考虑改用管道。

关于c# - StreamWriter 中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9599653/

相关文章:

java - 写入随机访问文件

c# - 写入后读取文件

c# - 在 StreamWriter 前面使用 'using'

c# - 通过 cookie 控制对页面的访问

c# - 为什么一个别名的 C# 类型不能被另一个访问?

c# - JsonSerializer.Deserialize 失败

c# - 文件 IO streamreader + streamwriter C# 的问题

c# - Azure 按需 Web 作业未收到格式正确的 json 序列化字符串

c# - 如何使用 LINQ C# 过滤列表

c# - 使用StreamReader/StreamWriter抓取日志导致程序停止响应