当前位置: 首页>>代码示例>>C#>>正文


C# Stream.SetLength方法代码示例

本文整理汇总了C#中System.IO.Stream.SetLength方法的典型用法代码示例。如果您正苦于以下问题:C# Stream.SetLength方法的具体用法?C# Stream.SetLength怎么用?C# Stream.SetLength使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.Stream的用法示例。


在下文中一共展示了Stream.SetLength方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CopyTo

        public void CopyTo(Stream stream)
        {
            // If the target stream allows seeking set its length upfront.
            // When writing to a large file, it helps to give a hint to the OS how big the file is going to be.
            if (stream.CanSeek)
            {
                stream.SetLength(stream.Position + _length);
            }

            int chunkIndex = 0;
            for (int remainingBytes = _length; remainingBytes > 0;)
            {
                int bytesToCopy = Math.Min(ChunkSize, remainingBytes);
                if (chunkIndex < _chunks.Count)
                {
                    stream.Write(_chunks[chunkIndex++], 0, bytesToCopy);
                }
                else
                {
                    // Fill remaining space with zero bytes
                    for (int i = 0; i < bytesToCopy; i++)
                    {
                        stream.WriteByte(0);
                    }
                }

                remainingBytes -= bytesToCopy;
            }
        }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:29,代码来源:ComMemoryStream.cs

示例2: Decode

        public void Decode(Stream source, Stream delta, Stream output)
        {
            using (BinaryReader deltaReader = new BinaryReader(delta))
            {
                long baseLength = deltaReader.ReadVarInteger();
                Debug.Assert(baseLength == source.Length);

                long resultLength = deltaReader.ReadVarInteger();
                output.SetLength(resultLength);

                while (delta.Position < delta.Length)
                {
                    byte cmd = deltaReader.ReadByte();
                    if ((cmd & COPY) != 0x00)
                    {
                        DoCopy(source, output, deltaReader, cmd);
                    }
                    else if(cmd != 0)
                    {
                        // 0 is reserved, but anything else is a length of data from the delta itself
                        byte[] data = deltaReader.ReadBytes(cmd);
                        output.Write(data, 0, data.Length);
                    }
                }
            }
            output.Flush();
        }
开发者ID:anurse,项目名称:Inversion,代码行数:27,代码来源:GitDeltaDecoder.cs

示例3: Write

		public void Write(Tag tag, Stream apeStream, Stream tempStream) {
			ByteBuffer tagBuffer = tc.Create(tag);

			if (!TagExists(apeStream)) {
				apeStream.Seek(0, SeekOrigin.End);
				apeStream.Write(tagBuffer.Data, 0, tagBuffer.Capacity);
			} else {
				apeStream.Seek( -32 + 8 , SeekOrigin.End);
			
				//Version
				byte[] b = new byte[4];
				apeStream.Read( b , 0,  b.Length);
				int version = Utils.GetNumber(b, 0, 3);
				if(version != 2000) {
					throw new CannotWriteException("APE Tag other than version 2.0 are not supported");
				}
				
				//Size
				b = new byte[4];
				apeStream.Read( b , 0,  b.Length);
				long oldSize = Utils.GetLongNumber(b, 0, 3) + 32;
				int tagSize = tagBuffer.Capacity;
				
				apeStream.Seek(-oldSize, SeekOrigin.End);
				apeStream.Write(tagBuffer.Data, 0, tagBuffer.Capacity);
					
				if(oldSize > tagSize) {
					//Truncate the file
					apeStream.SetLength(apeStream.Length - (oldSize-tagSize));
				}
			}
		}
开发者ID:emtees,项目名称:old-code,代码行数:32,代码来源:ApeTagWriter.cs

示例4: BlockStoreDiskCache

 /// <summary>
 /// Creates a new disk cache with the specified file name and capacity
 /// </summary>
 /// <param name="path">The full path to the disk cache file to be created</param>
 /// <param name="capacity">The number of blocks capacity for the store</param>
 /// <param name="blockSize">The size of individual blocks in the store</param>
 public BlockStoreDiskCache(string path, int capacity, int blockSize)
 {
     _blockSize = blockSize;
     _capacity = capacity;
     _path = path;
     bool retry = false;
     _fileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
     do
     {
         try
         {
             _fileLength = (long) _capacity*blockSize;
             _fileStream.SetLength(_fileLength);
             _blockLookup = new Dictionary<string, int>(_capacity);
             retry = false;
         }
         catch (IOException e)
         {
             Logging.LogWarning(BrightstarEventId.BlockProviderError,
                                "Could not create block cache file with capacity {0} due to exception {1}. Retrying with smaller capacity",
                                _capacity, e);
             _capacity = _capacity/2;
             retry = true;
         }
     } while (retry);
     Logging.LogInfo("Created block cache with capacity {0}", _capacity);
     _accessLock = new Mutex();
     _insertPoint = 0;
 }
开发者ID:Garwin4j,项目名称:BrightstarDB,代码行数:35,代码来源:BlockStoreDiskCache.cs

示例5: FileBufferingReadStream

        public FileBufferingReadStream(
            Stream inner,
            int memoryThreshold,
            long? bufferLimit,
            Func<string> tempFileDirectoryAccessor,
            ArrayPool<byte> bytePool)
        {
            if (inner == null)
            {
                throw new ArgumentNullException(nameof(inner));
            }

            if (tempFileDirectoryAccessor == null)
            {
                throw new ArgumentNullException(nameof(tempFileDirectoryAccessor));
            }

            _bytePool = bytePool;
            if (memoryThreshold < _maxRentedBufferSize)
            {
                _rentedBuffer = bytePool.Rent(memoryThreshold);
                _buffer = new MemoryStream(_rentedBuffer);
                _buffer.SetLength(0);
            }
            else
            {
                _buffer = new MemoryStream();
            }

            _inner = inner;
            _memoryThreshold = memoryThreshold;
            _bufferLimit = bufferLimit;
            _tempFileDirectoryAccessor = tempFileDirectoryAccessor;
        }
开发者ID:tuespetre,项目名称:HttpAbstractions,代码行数:34,代码来源:FileBufferingReadStream.cs

示例6: PatchStudy

        /// <summary>
        /// Studies and patches a stream.
        /// </summary>
        /// <param name="patch">The patch stream to study.</param>
        /// <param name="study">The study struct to use for patching.</param>
        /// <param name="source">The unpatched source stream.</param>
        /// <param name="target">The target stream to copy the source stream to, but with the patch applied.</param>
        public void PatchStudy(Stream patch, Studier.IpsStudy study, Stream source, Stream target)
        {
            source.CopyTo(target);
            long sourceLength = source.Length;
            if (study.Error == Studier.IpsError.IpsInvalid) throw new Exceptions.IpsInvalidException();
            int outlen = (int)Clamp(target.Length, study.OutlenMin, study.OutlenMax);
            // Set target file length to new size.
            target.SetLength(outlen);

            // Skip PATCH text.
            patch.Seek(5, SeekOrigin.Begin);
            int offset = Reader.Read24(patch);
            while (offset != EndOfFile)
            {
                int size = Reader.Read16(patch);

                target.Seek(offset, SeekOrigin.Begin);
                // If RLE patch.
                if (size == 0)
                {
                    size = Reader.Read16(patch);
                    target.Write(Enumerable.Repeat<byte>(Reader.Read8(patch), offset).ToArray(), 0, offset);
                }
                // If normal patch.
                else
                {
                    byte[] data = new byte[size];
                    patch.Read(data, 0, size);
                    target.Write(data, 0, size);

                }
                offset = Reader.Read24(patch);
            }
            if (study.OutlenMax != 0xFFFFFFFF && sourceLength <= study.OutlenMax) throw new Exceptions.IpsNotThisException(); // Truncate data without this being needed is a poor idea.
        }
开发者ID:vector-man,项目名称:tinyips,代码行数:42,代码来源:Patcher.cs

示例7: OneFileTransferModel

        protected OneFileTransferModel(int friendNumber, int fileNumber, string name,
            long fileSizeInBytes, TransferDirection direction, Stream stream, long transferredBytes = 0)
        {
            _stream = stream;
            if (_stream != null)
            {
                if (_stream.CanWrite)
                {
                    _stream.SetLength(fileSizeInBytes);
                }

                _stream.Position = transferredBytes;
            }
            _fileSizeInBytes = fileSizeInBytes;

            _direction = direction;
            SetInitialStateBasedOnDirection(direction);

            Name = name;

            _friendNumber = friendNumber;
            _fileNumber = fileNumber;

            ToxModel.Instance.FileControlReceived += FileControlReceivedHandler;
            ToxModel.Instance.FileChunkRequested += FileChunkRequestedHandler;
            ToxModel.Instance.FileChunkReceived += FileChunkReceivedHandler;
            ToxModel.Instance.FriendConnectionStatusChanged += FriendConnectionStatusChangedHandler;
            Application.Current.Suspending += AppSuspendingHandler;
        }
开发者ID:ProMcTagonist,项目名称:OneTox,代码行数:29,代码来源:OneFileTransferModel.cs

示例8: PdbWriter

    internal PdbWriter(Stream writer, int pageSize) {
      this.pageSize = pageSize;
      this.usedBytes = pageSize * 3;
      this.writer = writer;

      writer.SetLength(usedBytes);
    }
开发者ID:pusp,项目名称:o2platform,代码行数:7,代码来源:PdbWriter.cs

示例9: Delete

		public void Delete(Stream apeStream) {
			if(!TagExists(apeStream))
				return;
			
			apeStream.Seek( -20 , SeekOrigin.End);
			
			byte[] b = new byte[4];
			apeStream.Read( b , 0,  b.Length);
			long tagSize = Utils.GetLongNumber(b, 0, 3);
			
			apeStream.SetLength(apeStream.Length - tagSize);
			
			/* Check for a second header */
			if(!TagExists(apeStream))
				return;
			
			apeStream.SetLength(apeStream.Length - 32);
		}
开发者ID:emtees,项目名称:old-code,代码行数:18,代码来源:ApeTagWriter.cs

示例10: Backward

 /// <summary>
 ///     Вызов метода обнаружения и извлечения из информационного потока участка с переданными данными
 /// </summary>
 /// <param name="input">Входной поток данных</param>
 /// <param name="output">Выходной поток данных</param>
 public void Backward(Stream input, Stream output)
 {
     var length = new byte[4];
     input.Read(length, 0, length.Length);
     Int32 count = BitConverter.ToInt32(length, 0) & 0x7FFFFFFF;
     input.CopyTo(output);
     if (output.Length > count)
         output.SetLength(count);
 }
开发者ID:Scratch-net,项目名称:mssove2,代码行数:14,代码来源:Envelope.cs

示例11: SaveTo

 public Task SaveTo(Stream configurationData)
 {
     return Task.Run(() =>
     {
         var serializer = new DataContractJsonSerializer(typeof(Configuration));
         configurationData.Seek(0, SeekOrigin.Begin);
         serializer.WriteObject(configurationData, this);
         configurationData.SetLength(configurationData.Position);
     });
 }
开发者ID:pamidur,项目名称:Gpodder.NET,代码行数:10,代码来源:Configuration.cs

示例12: CopyStream

        /// <summary>
        /// Copies the bytes from this stream into another stream
        /// </summary>
        /// <param name="destination"></param>
        public static void CopyStream(this Stream source, Stream destination)
        {
            source.Position = 0;
            destination.SetLength(0L);

            byte[] buffer = new byte[8 * 1024];
            int readPosition;

            while ((readPosition = source.Read(buffer, 0, buffer.Length)) > 0)
                destination.Write(buffer, 0, readPosition);
        }
开发者ID:wduffy,项目名称:Toltech.Mvc,代码行数:15,代码来源:StreamExtensions.cs

示例13: CreateFixedVhdFile

        public static void CreateFixedVhdFile(Stream destination, long virtualSize)
        {
            var footer = VhdFooterFactory.CreateFixedDiskFooter(virtualSize);
            var serializer = new VhdFooterSerializer(footer);
            var buffer = serializer.ToByteArray();
            destination.SetLength(virtualSize + VhdConstants.VHD_FOOTER_SIZE);
            destination.Seek(-VhdConstants.VHD_FOOTER_SIZE, SeekOrigin.End);

            destination.Write(buffer, 0, buffer.Length);
            destination.Flush();
        }
开发者ID:huangpf,项目名称:azure-sdk-tools,代码行数:11,代码来源:CloudVhdFileCreator.cs

示例14: CreateFixedVhdFileAtAsync

        private static IEnumerable<CompletionPort> CreateFixedVhdFileAtAsync(AsyncMachine machine, Stream destination, long virtualSize)
        {
            var footer = VhdFooterFactory.CreateFixedDiskFooter(virtualSize);
            var serializer = new VhdFooterSerializer(footer);
            var buffer = serializer.ToByteArray();
            destination.SetLength(virtualSize + VhdConstants.VHD_FOOTER_SIZE);
            destination.Seek(-VhdConstants.VHD_FOOTER_SIZE, SeekOrigin.End);

            destination.BeginWrite(buffer, 0, buffer.Length, machine.CompletionCallback, null);
            yield return CompletionPort.SingleOperation;
            destination.EndWrite(machine.CompletionResult);
            destination.Flush();
        }
开发者ID:huangpf,项目名称:azure-sdk-tools,代码行数:13,代码来源:CloudVhdFileCreator.cs

示例15: Delete

 /// <summary>
 /// 删除流中的一块数据 。
 /// </summary>
 /// <param name="stream">目标流</param>
 /// <param name="position">起始位置</param>
 /// <param name="length">删除的长度</param>
 /// <returns>返回删除是否成功</returns>
 public static bool Delete(Stream stream, int position, int length)
 {
     if (stream == null || position < 0 || length <= 0) return false;
     if (position + length >= stream.Length)
         stream.SetLength(position);
     else
     {
         byte[] vBuffer = new byte[0x1000];
         int i = position;
         int l = 0;
         do
         {
             stream.Position = i + length;
             l = stream.Read(vBuffer, 0, vBuffer.Length);
             stream.Position = i;
             stream.Write(vBuffer, 0, l);
             i += l;
         }
         while (l >= vBuffer.Length);
         stream.SetLength(stream.Length - length);
     }
     return true;
 }
开发者ID:BlessingSoftware,项目名称:Controls,代码行数:30,代码来源:StreamEngine.cs


注:本文中的System.IO.Stream.SetLength方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。