加载大文件时出现 OutOfMemoryException

时间:2021-07-15 09:17:28

标签: c# json out-of-memory

我想就我收到的异常获得一些帮助。 我正在用 C# 4.7.2 编译 我有一个潜在的大文件,我需要加载它才能使用文件内容调用网络服务。但是加载这个文件最终会抛出一个 OutOfMemoryException。

我无法更改我正在调用的网络服务。

我想继续使用 JsonWriter,因为这是我发现在将 json 写入我的请求时避免另一个 OutOfMemoryException 的唯一方法。

我的代码:

// loading my file content
var fileContent = File.ReadAllText(path); // OutOfMemoryException throws here.

// Creating a httpWebRequest to post my file's content in a webservice
// myHttpWebRequest is of HttpWebRequest type

// I'm using the StreamWriter and JsonWriter in order to avoid throwing an OutOfMemoryException in the Json serialization when using a personalized object or a JObject with the ToString() method.
using (StreamWriter requestWriter = new StreamWriter(myHttpWebRequest.GetRequestStream(), new UTF8Encoding()))
using (JsonWriter writer = new JsonTextWriter(requestWriter))
{
    writer.Formatting = Newtonsoft.Json.Formatting.Indented;
    writer.WriteStartObject();
    writer.WritePropertyName("fileContent");
    writer.WriteValue(fileContent);
    // writing other properties and values in here
    writer.WriteEndObject();
}

// after this code there is no need of my file content anymore

通过查看不同的主题,我想我需要做一个 File.ReadAllLines 以便不将整个内容加载到内存中。这里的问题是我不知道如何在不加载完整字符串的情况下将其写入 JsonWriter ?

我想一种方法是摆脱 JsonWriter,使用 StringWriter 并手动创建 Json,但由于代码可读性,我希望我可以避免这种情况。

0 个答案:

没有答案
相关问题