Cannot edit generated excel fileCreate Generic method constraining T to an EnumHow to create Excel (.XLS and .XLSX) file in C# without installing Ms Office?How do I use reflection to call a generic method?Random number generator only generating one random numberHow can I generate random alphanumeric strings?Interop type cannot be embeddedHow do I generate a random int number?C# TCP file transfer - Images semi-transferredMonotouch: trying to play audio from a file that is generated on the fly using AVAudioPlayerStream writes only 512 bytes to a file on FTP server using C#

Divine apple island

How do I repair my stair bannister?

Proving a function is onto where f(x)=|x|.

Fuse symbol on toroidal transformer

How should I respond when I lied about my education and the company finds out through background check?

Did US corporations pay demonstrators in the German demonstrations against article 13?

Freedom of speech and where it applies

What does this horizontal bar at the first measure mean?

Engineer refusing to file/disclose patents

How can Trident be so inexpensive? Will it orbit Triton or just do a (slow) flyby?

Can somebody explain Brexit in a few child-proof sentences?

Query about absorption line spectra

List of people who lose a child in תנ"ך

Hot bath for aluminium engine block and heads

Should I install hardwood flooring or cabinets first?

Why does Async/Await work properly when the loop is inside the async function and not the other way around?

How will losing mobility of one hand affect my career as a programmer?

Has Darkwing Duck ever met Scrooge McDuck?

Why did the EU agree to delay the Brexit deadline?

A Permanent Norse Presence in America

Is it possible to use .desktop files to open local pdf files on specific pages with a browser?

Customize circled numbers

If a character with the Alert feat rolls a crit fail on their Perception check, are they surprised?

Gibbs free energy in standard state vs. equilibrium



Cannot edit generated excel file


Create Generic method constraining T to an EnumHow to create Excel (.XLS and .XLSX) file in C# without installing Ms Office?How do I use reflection to call a generic method?Random number generator only generating one random numberHow can I generate random alphanumeric strings?Interop type cannot be embeddedHow do I generate a random int number?C# TCP file transfer - Images semi-transferredMonotouch: trying to play audio from a file that is generated on the fly using AVAudioPlayerStream writes only 512 bytes to a file on FTP server using C#













0















Problem:

In installed Office 2010 computer, my app have to copy an empty excel file (file A) to new excel file (file B) and use OpenXML library (V2.5) to execute some action, finally saved to hard disk. After that I open file B and just add a litle bit data (for example: 1) to it and save and close it.

when I reopen file B, excel thrown an error: Excel found unreadable content in ' file B' do you want to recover the contents of this workbook... and I can not open it.

Below is my code:






static void Main(string[] args)

ExportDataSet(@"C:A.xlsx",@"C:");

public static void Copy(String oldPath, String newPath)

FileStream input = null;
FileStream output = null;
try

input = new FileStream(oldPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
output = new FileStream(newPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

var buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)

output.Write(buffer, 0, read);


catch (Exception e)


finally

if (input != null)

input.Close();
input.Dispose();

if (output != null)

output.Close();
output.Dispose();





public static string ExportDataSet(string filePath, string path, int startRow = 10)

var pathToSave = path;

if (!Directory.Exists(pathToSave))
Directory.CreateDirectory(pathToSave);
var filename = pathToSave + Guid.NewGuid() + Path.GetExtension(filePath);
Copy(filePath, filename);
var fs = File.Open(filename, FileMode.Open);

using (var myWorkbook = SpreadsheetDocument.Open(fs, true))

var workbookPart = myWorkbook.WorkbookPart;
var Sheets = myWorkbook.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
var relationshipId = Sheets.First().Id.Value;
var worksheetPart = (WorksheetPart)myWorkbook.WorkbookPart.GetPartById(relationshipId);
var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

workbookPart.Workbook.Save();
//workbookPart.Workbook.CalculationProperties = new CalculationProperties() FullCalculationOnLoad = true ;

fs.Close();
fs.Dispose();
return filename;





I think the OpenXML library has something wrong.
Do you have any ideas? please share to me, thank you so much.

Remarks:

1. the computer use Office 2010 to open Excel file

2. the file format is Excel workbook (.xlsx)

3. if the computer installed office with later version (2013, 2016), the problem was not appeared.








share|improve this question

















  • 1





    Not related to your problem, thats why I am not ading it to my answer, but you could handle your FileStream better, enclosing them in a using statement like you did with the workbook. That way you get sure you dont forget to dispose your resources, 'cause the framework already does it.

    – bradbury9
    Mar 7 at 9:27











  • You are probably focusing on the wrong part of the code when looking for the problem, OpenXML library is widely used, so unlikely to fail. I believe your problem is within your Copy(String oldPath, String newPath) method.

    – bradbury9
    Mar 7 at 9:30











  • @bradbury9 , I tried your code, but the problem was not resolve.

    – GIANGPZO
    Mar 7 at 9:37











  • 1- Does the problem happen with files smaller than your buffer size? 2- Maybe there is a bug in Office 2010 that does not conform to xlsx format, being able to open it with 2013 and later points to the file being fine.

    – bradbury9
    Mar 7 at 9:46











  • @bradbury9 I tried to copy empty excel file (file A) to new excel file (file B) without using OpenXML, after that I can open and edit file B normally without any problem. So I think problem in the code related to OpenXML.

    – GIANGPZO
    Mar 7 at 9:52















0















Problem:

In installed Office 2010 computer, my app have to copy an empty excel file (file A) to new excel file (file B) and use OpenXML library (V2.5) to execute some action, finally saved to hard disk. After that I open file B and just add a litle bit data (for example: 1) to it and save and close it.

when I reopen file B, excel thrown an error: Excel found unreadable content in ' file B' do you want to recover the contents of this workbook... and I can not open it.

Below is my code:






static void Main(string[] args)

ExportDataSet(@"C:A.xlsx",@"C:");

public static void Copy(String oldPath, String newPath)

FileStream input = null;
FileStream output = null;
try

input = new FileStream(oldPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
output = new FileStream(newPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

var buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)

output.Write(buffer, 0, read);


catch (Exception e)


finally

if (input != null)

input.Close();
input.Dispose();

if (output != null)

output.Close();
output.Dispose();





public static string ExportDataSet(string filePath, string path, int startRow = 10)

var pathToSave = path;

if (!Directory.Exists(pathToSave))
Directory.CreateDirectory(pathToSave);
var filename = pathToSave + Guid.NewGuid() + Path.GetExtension(filePath);
Copy(filePath, filename);
var fs = File.Open(filename, FileMode.Open);

using (var myWorkbook = SpreadsheetDocument.Open(fs, true))

var workbookPart = myWorkbook.WorkbookPart;
var Sheets = myWorkbook.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
var relationshipId = Sheets.First().Id.Value;
var worksheetPart = (WorksheetPart)myWorkbook.WorkbookPart.GetPartById(relationshipId);
var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

workbookPart.Workbook.Save();
//workbookPart.Workbook.CalculationProperties = new CalculationProperties() FullCalculationOnLoad = true ;

fs.Close();
fs.Dispose();
return filename;





I think the OpenXML library has something wrong.
Do you have any ideas? please share to me, thank you so much.

Remarks:

1. the computer use Office 2010 to open Excel file

2. the file format is Excel workbook (.xlsx)

3. if the computer installed office with later version (2013, 2016), the problem was not appeared.








share|improve this question

















  • 1





    Not related to your problem, thats why I am not ading it to my answer, but you could handle your FileStream better, enclosing them in a using statement like you did with the workbook. That way you get sure you dont forget to dispose your resources, 'cause the framework already does it.

    – bradbury9
    Mar 7 at 9:27











  • You are probably focusing on the wrong part of the code when looking for the problem, OpenXML library is widely used, so unlikely to fail. I believe your problem is within your Copy(String oldPath, String newPath) method.

    – bradbury9
    Mar 7 at 9:30











  • @bradbury9 , I tried your code, but the problem was not resolve.

    – GIANGPZO
    Mar 7 at 9:37











  • 1- Does the problem happen with files smaller than your buffer size? 2- Maybe there is a bug in Office 2010 that does not conform to xlsx format, being able to open it with 2013 and later points to the file being fine.

    – bradbury9
    Mar 7 at 9:46











  • @bradbury9 I tried to copy empty excel file (file A) to new excel file (file B) without using OpenXML, after that I can open and edit file B normally without any problem. So I think problem in the code related to OpenXML.

    – GIANGPZO
    Mar 7 at 9:52













0












0








0








Problem:

In installed Office 2010 computer, my app have to copy an empty excel file (file A) to new excel file (file B) and use OpenXML library (V2.5) to execute some action, finally saved to hard disk. After that I open file B and just add a litle bit data (for example: 1) to it and save and close it.

when I reopen file B, excel thrown an error: Excel found unreadable content in ' file B' do you want to recover the contents of this workbook... and I can not open it.

Below is my code:






static void Main(string[] args)

ExportDataSet(@"C:A.xlsx",@"C:");

public static void Copy(String oldPath, String newPath)

FileStream input = null;
FileStream output = null;
try

input = new FileStream(oldPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
output = new FileStream(newPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

var buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)

output.Write(buffer, 0, read);


catch (Exception e)


finally

if (input != null)

input.Close();
input.Dispose();

if (output != null)

output.Close();
output.Dispose();





public static string ExportDataSet(string filePath, string path, int startRow = 10)

var pathToSave = path;

if (!Directory.Exists(pathToSave))
Directory.CreateDirectory(pathToSave);
var filename = pathToSave + Guid.NewGuid() + Path.GetExtension(filePath);
Copy(filePath, filename);
var fs = File.Open(filename, FileMode.Open);

using (var myWorkbook = SpreadsheetDocument.Open(fs, true))

var workbookPart = myWorkbook.WorkbookPart;
var Sheets = myWorkbook.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
var relationshipId = Sheets.First().Id.Value;
var worksheetPart = (WorksheetPart)myWorkbook.WorkbookPart.GetPartById(relationshipId);
var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

workbookPart.Workbook.Save();
//workbookPart.Workbook.CalculationProperties = new CalculationProperties() FullCalculationOnLoad = true ;

fs.Close();
fs.Dispose();
return filename;





I think the OpenXML library has something wrong.
Do you have any ideas? please share to me, thank you so much.

Remarks:

1. the computer use Office 2010 to open Excel file

2. the file format is Excel workbook (.xlsx)

3. if the computer installed office with later version (2013, 2016), the problem was not appeared.








share|improve this question














Problem:

In installed Office 2010 computer, my app have to copy an empty excel file (file A) to new excel file (file B) and use OpenXML library (V2.5) to execute some action, finally saved to hard disk. After that I open file B and just add a litle bit data (for example: 1) to it and save and close it.

when I reopen file B, excel thrown an error: Excel found unreadable content in ' file B' do you want to recover the contents of this workbook... and I can not open it.

Below is my code:






static void Main(string[] args)

ExportDataSet(@"C:A.xlsx",@"C:");

public static void Copy(String oldPath, String newPath)

FileStream input = null;
FileStream output = null;
try

input = new FileStream(oldPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
output = new FileStream(newPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

var buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)

output.Write(buffer, 0, read);


catch (Exception e)


finally

if (input != null)

input.Close();
input.Dispose();

if (output != null)

output.Close();
output.Dispose();





public static string ExportDataSet(string filePath, string path, int startRow = 10)

var pathToSave = path;

if (!Directory.Exists(pathToSave))
Directory.CreateDirectory(pathToSave);
var filename = pathToSave + Guid.NewGuid() + Path.GetExtension(filePath);
Copy(filePath, filename);
var fs = File.Open(filename, FileMode.Open);

using (var myWorkbook = SpreadsheetDocument.Open(fs, true))

var workbookPart = myWorkbook.WorkbookPart;
var Sheets = myWorkbook.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
var relationshipId = Sheets.First().Id.Value;
var worksheetPart = (WorksheetPart)myWorkbook.WorkbookPart.GetPartById(relationshipId);
var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

workbookPart.Workbook.Save();
//workbookPart.Workbook.CalculationProperties = new CalculationProperties() FullCalculationOnLoad = true ;

fs.Close();
fs.Dispose();
return filename;





I think the OpenXML library has something wrong.
Do you have any ideas? please share to me, thank you so much.

Remarks:

1. the computer use Office 2010 to open Excel file

2. the file format is Excel workbook (.xlsx)

3. if the computer installed office with later version (2013, 2016), the problem was not appeared.




static void Main(string[] args)

ExportDataSet(@"C:A.xlsx",@"C:");

public static void Copy(String oldPath, String newPath)

FileStream input = null;
FileStream output = null;
try

input = new FileStream(oldPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
output = new FileStream(newPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

var buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)

output.Write(buffer, 0, read);


catch (Exception e)


finally

if (input != null)

input.Close();
input.Dispose();

if (output != null)

output.Close();
output.Dispose();





public static string ExportDataSet(string filePath, string path, int startRow = 10)

var pathToSave = path;

if (!Directory.Exists(pathToSave))
Directory.CreateDirectory(pathToSave);
var filename = pathToSave + Guid.NewGuid() + Path.GetExtension(filePath);
Copy(filePath, filename);
var fs = File.Open(filename, FileMode.Open);

using (var myWorkbook = SpreadsheetDocument.Open(fs, true))

var workbookPart = myWorkbook.WorkbookPart;
var Sheets = myWorkbook.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
var relationshipId = Sheets.First().Id.Value;
var worksheetPart = (WorksheetPart)myWorkbook.WorkbookPart.GetPartById(relationshipId);
var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

workbookPart.Workbook.Save();
//workbookPart.Workbook.CalculationProperties = new CalculationProperties() FullCalculationOnLoad = true ;

fs.Close();
fs.Dispose();
return filename;






static void Main(string[] args)

ExportDataSet(@"C:A.xlsx",@"C:");

public static void Copy(String oldPath, String newPath)

FileStream input = null;
FileStream output = null;
try

input = new FileStream(oldPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
output = new FileStream(newPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

var buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)

output.Write(buffer, 0, read);


catch (Exception e)


finally

if (input != null)

input.Close();
input.Dispose();

if (output != null)

output.Close();
output.Dispose();





public static string ExportDataSet(string filePath, string path, int startRow = 10)

var pathToSave = path;

if (!Directory.Exists(pathToSave))
Directory.CreateDirectory(pathToSave);
var filename = pathToSave + Guid.NewGuid() + Path.GetExtension(filePath);
Copy(filePath, filename);
var fs = File.Open(filename, FileMode.Open);

using (var myWorkbook = SpreadsheetDocument.Open(fs, true))

var workbookPart = myWorkbook.WorkbookPart;
var Sheets = myWorkbook.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
var relationshipId = Sheets.First().Id.Value;
var worksheetPart = (WorksheetPart)myWorkbook.WorkbookPart.GetPartById(relationshipId);
var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

workbookPart.Workbook.Save();
//workbookPart.Workbook.CalculationProperties = new CalculationProperties() FullCalculationOnLoad = true ;

fs.Close();
fs.Dispose();
return filename;







c# openxml openxml-sdk






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 7 at 8:58









GIANGPZOGIANGPZO

125216




125216







  • 1





    Not related to your problem, thats why I am not ading it to my answer, but you could handle your FileStream better, enclosing them in a using statement like you did with the workbook. That way you get sure you dont forget to dispose your resources, 'cause the framework already does it.

    – bradbury9
    Mar 7 at 9:27











  • You are probably focusing on the wrong part of the code when looking for the problem, OpenXML library is widely used, so unlikely to fail. I believe your problem is within your Copy(String oldPath, String newPath) method.

    – bradbury9
    Mar 7 at 9:30











  • @bradbury9 , I tried your code, but the problem was not resolve.

    – GIANGPZO
    Mar 7 at 9:37











  • 1- Does the problem happen with files smaller than your buffer size? 2- Maybe there is a bug in Office 2010 that does not conform to xlsx format, being able to open it with 2013 and later points to the file being fine.

    – bradbury9
    Mar 7 at 9:46











  • @bradbury9 I tried to copy empty excel file (file A) to new excel file (file B) without using OpenXML, after that I can open and edit file B normally without any problem. So I think problem in the code related to OpenXML.

    – GIANGPZO
    Mar 7 at 9:52












  • 1





    Not related to your problem, thats why I am not ading it to my answer, but you could handle your FileStream better, enclosing them in a using statement like you did with the workbook. That way you get sure you dont forget to dispose your resources, 'cause the framework already does it.

    – bradbury9
    Mar 7 at 9:27











  • You are probably focusing on the wrong part of the code when looking for the problem, OpenXML library is widely used, so unlikely to fail. I believe your problem is within your Copy(String oldPath, String newPath) method.

    – bradbury9
    Mar 7 at 9:30











  • @bradbury9 , I tried your code, but the problem was not resolve.

    – GIANGPZO
    Mar 7 at 9:37











  • 1- Does the problem happen with files smaller than your buffer size? 2- Maybe there is a bug in Office 2010 that does not conform to xlsx format, being able to open it with 2013 and later points to the file being fine.

    – bradbury9
    Mar 7 at 9:46











  • @bradbury9 I tried to copy empty excel file (file A) to new excel file (file B) without using OpenXML, after that I can open and edit file B normally without any problem. So I think problem in the code related to OpenXML.

    – GIANGPZO
    Mar 7 at 9:52







1




1





Not related to your problem, thats why I am not ading it to my answer, but you could handle your FileStream better, enclosing them in a using statement like you did with the workbook. That way you get sure you dont forget to dispose your resources, 'cause the framework already does it.

– bradbury9
Mar 7 at 9:27





Not related to your problem, thats why I am not ading it to my answer, but you could handle your FileStream better, enclosing them in a using statement like you did with the workbook. That way you get sure you dont forget to dispose your resources, 'cause the framework already does it.

– bradbury9
Mar 7 at 9:27













You are probably focusing on the wrong part of the code when looking for the problem, OpenXML library is widely used, so unlikely to fail. I believe your problem is within your Copy(String oldPath, String newPath) method.

– bradbury9
Mar 7 at 9:30





You are probably focusing on the wrong part of the code when looking for the problem, OpenXML library is widely used, so unlikely to fail. I believe your problem is within your Copy(String oldPath, String newPath) method.

– bradbury9
Mar 7 at 9:30













@bradbury9 , I tried your code, but the problem was not resolve.

– GIANGPZO
Mar 7 at 9:37





@bradbury9 , I tried your code, but the problem was not resolve.

– GIANGPZO
Mar 7 at 9:37













1- Does the problem happen with files smaller than your buffer size? 2- Maybe there is a bug in Office 2010 that does not conform to xlsx format, being able to open it with 2013 and later points to the file being fine.

– bradbury9
Mar 7 at 9:46





1- Does the problem happen with files smaller than your buffer size? 2- Maybe there is a bug in Office 2010 that does not conform to xlsx format, being able to open it with 2013 and later points to the file being fine.

– bradbury9
Mar 7 at 9:46













@bradbury9 I tried to copy empty excel file (file A) to new excel file (file B) without using OpenXML, after that I can open and edit file B normally without any problem. So I think problem in the code related to OpenXML.

– GIANGPZO
Mar 7 at 9:52





@bradbury9 I tried to copy empty excel file (file A) to new excel file (file B) without using OpenXML, after that I can open and edit file B normally without any problem. So I think problem in the code related to OpenXML.

– GIANGPZO
Mar 7 at 9:52












1 Answer
1






active

oldest

votes


















0














Your buffer reading and writting logic is wrong. The second parameter is where it starts to read or write and you are passing it a zero value, so second iteration of the while is overwritting the content written in the first iteration thus you are getting corrupted data if the files are greater than your buffer size.



Your code should be similar to this:



var buffer = new byte[32768];
int totalRead = 0; // Variable to track where to write in the next while iteration
int read;
while ((read = input.Read(buffer, totalRead, buffer.Length)) > 0)

output.Write(buffer, totalRead, read);
totalRead += read; // Add to totalRead the amount written so next iteration does append the content at the end.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55039721%2fcannot-edit-generated-excel-file%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Your buffer reading and writting logic is wrong. The second parameter is where it starts to read or write and you are passing it a zero value, so second iteration of the while is overwritting the content written in the first iteration thus you are getting corrupted data if the files are greater than your buffer size.



    Your code should be similar to this:



    var buffer = new byte[32768];
    int totalRead = 0; // Variable to track where to write in the next while iteration
    int read;
    while ((read = input.Read(buffer, totalRead, buffer.Length)) > 0)

    output.Write(buffer, totalRead, read);
    totalRead += read; // Add to totalRead the amount written so next iteration does append the content at the end.






    share|improve this answer





























      0














      Your buffer reading and writting logic is wrong. The second parameter is where it starts to read or write and you are passing it a zero value, so second iteration of the while is overwritting the content written in the first iteration thus you are getting corrupted data if the files are greater than your buffer size.



      Your code should be similar to this:



      var buffer = new byte[32768];
      int totalRead = 0; // Variable to track where to write in the next while iteration
      int read;
      while ((read = input.Read(buffer, totalRead, buffer.Length)) > 0)

      output.Write(buffer, totalRead, read);
      totalRead += read; // Add to totalRead the amount written so next iteration does append the content at the end.






      share|improve this answer



























        0












        0








        0







        Your buffer reading and writting logic is wrong. The second parameter is where it starts to read or write and you are passing it a zero value, so second iteration of the while is overwritting the content written in the first iteration thus you are getting corrupted data if the files are greater than your buffer size.



        Your code should be similar to this:



        var buffer = new byte[32768];
        int totalRead = 0; // Variable to track where to write in the next while iteration
        int read;
        while ((read = input.Read(buffer, totalRead, buffer.Length)) > 0)

        output.Write(buffer, totalRead, read);
        totalRead += read; // Add to totalRead the amount written so next iteration does append the content at the end.






        share|improve this answer















        Your buffer reading and writting logic is wrong. The second parameter is where it starts to read or write and you are passing it a zero value, so second iteration of the while is overwritting the content written in the first iteration thus you are getting corrupted data if the files are greater than your buffer size.



        Your code should be similar to this:



        var buffer = new byte[32768];
        int totalRead = 0; // Variable to track where to write in the next while iteration
        int read;
        while ((read = input.Read(buffer, totalRead, buffer.Length)) > 0)

        output.Write(buffer, totalRead, read);
        totalRead += read; // Add to totalRead the amount written so next iteration does append the content at the end.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 7 at 9:28

























        answered Mar 7 at 9:21









        bradbury9bradbury9

        1,43321820




        1,43321820





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55039721%2fcannot-edit-generated-excel-file%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

            Алба-Юлія

            Захаров Федір Захарович