Problem writing segmented files

I upload parts of a file (image), and then I want to save these parts to a single file.

The problem is that the first part is loading and saving properly (I see part of this appeal). But, when the second part is saved (FileMode.Append), the image seems to be broken.

Here is the code:

  HttpWebRequest webRequest;
  HttpWebResponse webResponse;
  Stream responseStream;
  long StartPosition, EndPosition;

        if (File.Exists(LocalPath))
            fileStream = new FileStream(LocalPath, FileMode.Append);
        else fileStream = new FileStream(LocalPath, FileMode.Create);

        webRequest = (HttpWebRequest)WebRequest.Create(FileURL);

        webResponse = (HttpWebResponse)webRequest.GetResponse();
        responseStream = webResponse.GetResponseStream();

        StartPosition = 0;   //download first 52062 bytes of the file
        EndPosition = 52061;

        webRequest.AddRange(StartPosition, EndPosition);

        int SeekPosition = (int)StartPosition;

        while ((bytesSize = responseStream.Read(Buffer, 0, Buffer.Length)) > 0)
        {
            lock (fileStream)
            {
                fileStream.Seek(SeekPosition, SeekOrigin.Begin);
                fileStream.Write(Buffer,0, bytesSize);
            }

  //the Buffer.Length is 2048.
  //When the bytes count to download is < 2048 then I decrease the Buffer.Length
  //to prevent downloading more that 52062 bytes.

            DownloadedBytesCount += bytesSize;
            SeekPosition += bytesSize;

            long TotalToDownload = EndPosition - StartPosition;

            long bytesLeft = TotalToDownload - DownloadedBytesCount;

            if (bytesLeft < Buffer.Length)
                Buffer = new byte[bytesLeft];
        }

When I want to download the second part of the file that I installed

    StartPosition = 52062;
    EndPosition = 104122;

and then the problem described above arises. Why is the file not attached properly?

-2
source share
3 answers

You do not need StartPosition, fileStream.Seek()andBuffer = new byte[bytesLeft];

Also not necessary lock()(if you have problems with a lot of problems).

So, delete all this, because there is a possibility that you were mistaken.

- , . :

  • , .
  • 52k - 104k
  • ?
  • 52k ?
  • ..

, .

+2

- , , , , , ...

0

Source: https://habr.com/ru/post/1763317/


All Articles