ZIP file gets damaged after uploading to SharePoint

  • Thread starter Thread starter LeonardoS98
  • Start date Start date
L

LeonardoS98

Guest
I'm currently trying to upload a .zip file to SharePoint online. But for some reason the file gets corrupted every time, it receives there. In other words, the file is fine before the upload and gets corrupted during the transfer and appears on my SharePoint site as a regular .zip file. But as soon as I want to open it, I get a message saying that the file got damaged.

I already searched on stackoverflow but it seems like no answer fits my problem. But what I read was, that the problem has something to do with my stream. So I guess its somewhere inside the using(MemoryStream contentStream.... ). I know that I should use Stream to upload zip files, but I didn't find a way to build around them...


// Use large file upload approach.
ClientResult<long> bytesUploaded = null;

FileStream fs = null;
try
{
fs = System.IO.File.Open(uploadFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using(BinaryReader br = new BinaryReader(fs))
{
byte[] buffer = new byte[blockSize];
Byte[] lastBuffer = null;
long fileoffset = 0;
long totalBytesRead = 0;
int bytesRead;
bool first = true;
bool last = false;

// Read data from file system in blocks
while((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)
{
totalBytesRead = totalBytesRead + bytesRead;

// You've reached the end of the file.
if(totalBytesRead == fileSize)
{
last = true;
// Copy to a new buffer the has the correct size.
lastBuffer = new byte[bytesRead];
Array.Copy(buffer, 0, lastBuffer, 0, bytesRead);
}

if (first)
{
using(MemoryStream contentStream = new MemoryStream())
{
// Add an empty file
FileCreationInformation fileInfo = new FileCreationInformation();
fileInfo.ContentStream = contentStream;
fileInfo.Url = sharePointRoot + sharePointSite + "/" + jahr + "/" + monat + "/" + uniqueFileName;
fileInfo.Overwrite = true;
uploadFile = docs.RootFolder.Files.Add(fileInfo);

// Start upload by uploading the first slice.
using(MemoryStream s = new MemoryStream(buffer))
{
// Call the start upload method on the first slice.
bytesUploaded = uploadFile.StartUpload(uploadId, s);
ctx.ExecuteQuery();
// fileoffset is the pointer where next slice will be added.
fileoffset = bytesUploaded.Value;
}

// You can only start the upload once.
first = false;
}
}
else
{
// Get a reference to your file.
uploadFile = ctx.Web.GetFileByServerRelativeUrl(docs.RootFolder.ServerRelativeUrl + "/" + jahr + "/" + monat + "/" + uniqueFileName);

if (last)
{
// IS this the last slice of data?
using (MemoryStream s = new MemoryStream(lastBuffer))
{
// Continue sliced upload.
bytesUploaded = uploadFile.ContinueUpload(uploadId, fileoffset, s);
ctx.ExecuteQuery();
// Update fileoffset for the next slice.
fileoffset = bytesUploaded.Value;
}
}
}
} // while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)
}
}

Continue reading...
 
Back
Top