BoldSign®Effortlessly integrate e-signatures into your app with the BoldSign® API. Create a sandbox account!
Hi,
I open a .docx file with the Document Editor and make changes to it. When I save the modified file with the same name in the same directory, the .docx file becomes corrupted. However, if I save it in a different directory, the .docx file does not get corrupted. I want to save it with the same name in the same directory without corruption.
Hello,
We have noticed that you might be attempting to save a document using the following code:
public async Task<bool> Export([FromBody] CustomParameter param) { try { string path = this.hostEnvironment.ContentRootPath + "\\Files\\" + param.fileName; using Stream document = Syncfusion.EJ2.DocumentEditor.WordDocument.Save(param.documentData, Syncfusion.EJ2.DocumentEditor.FormatType.Docx); using FileStream file = new(path, FileMode.OpenOrCreate, FileAccess.Write); await document.CopyToAsync(file).ConfigureAwait(false); return true; } catch (Exception e) { // Handle exception, log it if necessary return false; } } |
The problem of file corruption when overwriting an existing file in your code likely arises from the use of FileMode.OpenOrCreate in the FileStream constructor. This mode opens the file if it exists or creates a new one if it doesn't. When you overwrite an existing file with this mode, the new content might not fully replace the old content, especially if it is smaller, leaving residual data from the original file and causing corruption.
To ensure the file is correctly overwritten, please use FileMode.Create instead of FileMode.OpenOrCreate. FileMode.Create will always create a new file, and if the file already exists, it will be overwritten and truncated to zero length before writing the new content. This guarantees that no residual data from the original file remains.
Here is the updated code:
public async Task<bool> Export([FromBody] CustomParameter param) { try { string path = this.hostEnvironment.ContentRootPath + "\\Files\\" + param.fileName; using Stream document = Syncfusion.EJ2.DocumentEditor.WordDocument.Save(param.documentData, Syncfusion.EJ2.DocumentEditor.FormatType.Docx); // Use FileMode.Create to ensure the file is properly overwritten using FileStream file = new(path, FileMode.Create, FileAccess.Write); await document.CopyToAsync(file).ConfigureAwait(false); return true; } catch (Exception e) { // Handle exception, log it if necessary return false; } } |
This adjustment will help prevent file corruption by ensuring the file is always correctly overwritten.
You can also resolve this issue by setting the filestream length to 0 and then closing the filestream. Please refer the below image attached for your reference.
Regards,
Mohammed Affan C