问题
I want to generate a string and then write it in to a .txt file. The problem is I get OutOfMemory exceptions when I attempt to do so.
The file is large (about 10000 lines).
I use String.Format
and loops to create the string. How can I write this to a .txt file?
string Text= @"...";
const string channelScalar = @"...";
Text= string.Format(...);
foreach (Channel channel in ...)
{
switch (channel.Type)
{
case "...":
Text= string.Format(Text,
ChannelFrames(channel, string.Format(...);
break;
}
}
File.WriteAllText(textBox9.Text,Text);
回答1:
Use a StreamWriter
to directly write each line you generate into the textfile. This avoids storing the whole long file in memory first.
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\Somewhere\\whatever.txt"))
{
//Generate all the single lines and write them directly into the file
for (int i = 0; i<=10000;i++)
{
sw.WriteLine("This is such a nice line of text. *snort*");
}
}
来源:https://stackoverflow.com/questions/30536982/outofmemory-exception-thrown-while-writing-large-text-file