簡體   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