@@ -146,18 +146,28 @@ public virtual void SaveSettings() {
146146 Directory . CreateDirectory ( Path . GetDirectoryName ( path ) ) ;
147147
148148 try {
149- using ( FileStream stream = File . OpenWrite ( path ) ) {
150- if ( _Settings is EverestModuleBinarySettings ) {
151- using ( BinaryWriter writer = new BinaryWriter ( stream ) ) {
152- ( ( EverestModuleBinarySettings ) _Settings ) . Write ( writer ) ;
153- if ( forceFlush || ( ( CoreModule . Settings . SaveDataFlush ?? true ) && ! MainThreadHelper . IsMainThread ) )
154- stream . Flush ( true ) ;
149+ using ( FileStream fileStream = File . OpenWrite ( path ) ) {
150+ if ( _Settings is EverestModuleBinarySettings settings ) {
151+ using ( BinaryWriter binaryWriter = new BinaryWriter ( fileStream ) ) {
152+ settings . Write ( binaryWriter ) ;
153+ if ( forceFlush || ( ( CoreModule . Settings . SaveDataFlush ?? true ) && ! MainThreadHelper . IsMainThread ) ) {
154+ // first flush the binaryWriter to the fileStream then flush the fileStream
155+ // otherwise some data may remain buffered in the binaryWriter
156+ // and cause additional writes to the file
157+ binaryWriter . Flush ( ) ;
158+ fileStream . Flush ( true ) ;
159+ }
155160 }
156161 } else {
157- using ( StreamWriter writer = new StreamWriter ( stream ) ) {
158- YamlHelper . Serializer . Serialize ( writer , _Settings , SettingsType ) ;
159- if ( forceFlush || ( ( CoreModule . Settings . SaveDataFlush ?? true ) && ! MainThreadHelper . IsMainThread ) )
160- stream . Flush ( true ) ;
162+ using ( StreamWriter streamWriter = new StreamWriter ( fileStream ) ) {
163+ YamlHelper . Serializer . Serialize ( streamWriter , _Settings , SettingsType ) ;
164+ if ( forceFlush || ( ( CoreModule . Settings . SaveDataFlush ?? true ) && ! MainThreadHelper . IsMainThread ) ) {
165+ // first flush the streamWriter to the fileStream then flush the fileStream
166+ // otherwise some data may remain buffered in the streamWriter
167+ // and cause additional writes to the file
168+ streamWriter . Flush ( ) ;
169+ fileStream . Flush ( true ) ;
170+ }
161171 }
162172 }
163173 }
0 commit comments