繁体   English   中英

将流写入文件和内存

[英]Writing a stream to a File and to memory

我正在尝试读取EmbeddedResource(默认配置文件)并将其写入文件。 在那之后,我应该阅读文件并为了使事情变得更容易,我决定一步一步地做到这一点。

    private string CreateDefaultFile()
    {
        using (var stream = Shelter.Assembly.GetManifestResourceStream($@"Mod.Resources.Config.{_file}"))
        {
            if (stream == null)
                throw new NullReferenceException(); //TODO
            using (var ms = new MemoryStream())
            {
                using (var fs = new FileStream(Shelter.ModDirectory + _file, FileMode.Create, FileAccess.Write, FileShare.Read))
                {
                    byte[] buffer = new byte[512];

                    int bytesRead;
                    while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, bytesRead);
                        fs.Write(buffer, 0, bytesRead);
                    }

                    fs.Flush();
                    ms.Flush();

                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
        }
    }

这确实创建了文件,但是返回值似乎并没有正常工作。 内容似乎正确,但JSON.Net无法使用以下错误对其进行解析: JsonReaderException: Unexpected character encountered while parsing value: . Path '', line 0, position 0. JsonReaderException: Unexpected character encountered while parsing value: . Path '', line 0, position 0. 使用File.ReadAllText(...)而不是Encoding.UTF8.GetString(ms.ToArray())似乎可以工作,所以我猜测这是将流加载到字符串中的问题。

另外,由于文件较小,因此不需要分块部分。我在多个位置进行了更好的阅读,所以我更喜欢它。

(定位.NET Framework 3.5

多亏了dbc评论和Tergiver的回答,我解决了这个问题。

编码:

private string CreateDefaultFile()
{
    using (var stream = Shelter.Assembly.GetManifestResourceStream($@"Mod.Resources.Config.{_file}"))
    {
        if (stream == null)
            throw new NullReferenceException(); //TODO
        using (var ms = new MemoryStream())
        {
            using (var fs = File.Open(Shelter.ModDirectory + _file, FileMode.Create, FileAccess.Write, FileShare.Read))
            {
                byte[] buffer = new byte[512];

                int bytesRead;
                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, bytesRead);
                    fs.Write(buffer, 0, bytesRead);
                }

                fs.Flush();
                ms.Flush();

                byte[] content = ms.ToArray();
                if (content.Length >= 3 && content[0] == 0xEF && content[1] == 0xBB && content[2] == 0xBF)
                    return Encoding.UTF8.GetString(content, 3, content.Length - 3);
                return Encoding.UTF8.GetString(content);
            }
        }
    }
}

暂无
暂无

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

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