1

here is my code :

string json = JsonConvert.SerializeObject(stocksArticles,Formatting.Indented);
StreamWriter sw = new StreamWriter("Export\\Stocks.json");
sw.Write(json);

it's working fine but the json file is not complete it's look like the StreamWriter stop before the end, this is the end of the file :

{ "Reference": "999840", "Stocks": { "S": 0.0 } }, { "

i dont understand why it's stopping, i tried to define the buffersize for the StreamWriter but no effect.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
ced
  • 23
  • 4

2 Answers2

1

This is a common sign of not flushing/closing the stream (it is quite common for streams to maintain some buffer for performance reasons). You can do something like:

StreamWriter sw = new StreamWriter("Export\\Stocks.json");
sw.Write(json);
sw.Close();

But far more correct approach is to use using which will dispose the resource correctly:

using (StreamWriter sw = new StreamWriter("Export\\Stocks.json"))
{
    sw.Write(json);
}

Read more:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
-1

you don't need any stremwriter. just try this code

File.WriteAllText(@"Export\Stocks.json",json);
Serge
  • 40,935
  • 4
  • 18
  • 45
  • 2
    Arguably they *do* need one, because they should serialize directly to a stream rather than into a string – Charlieface May 15 '23 at 15:26
  • @Charlieface Is this serialized directly to a stream string json = JsonConvert.SerializeObject(stocksArticles,Formatting.Indented); ??? You should think at first and post a comment the second – Serge May 15 '23 at 21:04
  • 2
    No it isn't. But I said *should* not *did*: in other words they should instead still keep the writer so that they can serialize directly without going via a string. – Charlieface May 15 '23 at 21:16