FileStream writing buffer to file

I'm trying to upload a .srt file through an API that takes File as a parameter.

The file is stored on the server, and I'm using FileStream and StreamWriter to write to it:

string path = Server.MapPath("~/App_Data/captions/" + entryId) + ".srt";
FileStream f = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter s = new StreamWriter(f);

s.Write(someString);
f.Flush()

// Connecting to API and uploading the file

s.Close();

However, even though the file is created correctly on my server, the uploaded file is empty. If the file already exists, it will upload that file correctly but only contain the existing content, and not the additional text I added from someString.

I thought f.Flush() would ensure that the data in StreamWriter is written and saved to the file, but that doesn't seem to be the case.

What do I have to do to make sure that the data is written to the file before it is uploaded through the API?

Jon Skeet
people
quotationmark

You're currently flushing f, but not s. You're flushing the FileStream, but the StreamWriter wraps that, so it could easily have its own buffer. Don't forget that the FileStream doesn't know anything about the StreamWriter - the relationship is the other way round.

It's not clear why you're uploading the file before you close the StreamWriter, to be honest. I would just use:

File.WriteAllText(path, someString);
// Upload it now

If you do definitely want to use FileStream and StreamWriter, I'd strongly advise you to use using statements instead of manually closing things, too...

people

See more on this question at Stackoverflow