SetLength() public abstract method

public abstract SetLength ( long value ) : void
value long
return void
Example #1
0
        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;
            }
        }
Example #2
0
		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));
				}
			}
		}
Example #3
0
    internal PdbWriter(Stream writer, int pageSize) {
      this.pageSize = pageSize;
      this.usedBytes = pageSize * 3;
      this.writer = writer;

      writer.SetLength(usedBytes);
    }
Example #4
0
        /// <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.
        }
        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;
        }
Example #6
0
        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();
        }
 /// <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;
 }
        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;
        }
Example #9
0
		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);
		}
Example #10
0
 /// <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);
 }
Example #11
0
 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);
     });
 }
        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();
        }
Example #13
0
        /// <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);
        }
        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();
        }
Example #15
0
 static public int SetLength(IntPtr l)
 {
     try {
         System.IO.Stream self = (System.IO.Stream)checkSelf(l);
         System.Int64     a1;
         checkType(l, 2, out a1);
         self.SetLength(a1);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Example #16
0
 /// <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;
 }
Example #17
0
        public static async Task<ArchiveWriter> CreateAsync(Stream stream, bool dispose)
        {
            try
            {
                var writer = new ArchiveWriter(stream, dispose);

                stream.Position = 0;
                stream.SetLength(ArchiveMetadataFormat.kHeaderLength);
                await stream.WriteAsync(writer.PrepareHeader(), 0, ArchiveMetadataFormat.kHeaderLength).ConfigureAwait(false);

                return writer;
            }
            catch
            {
                if (dispose && stream != null)
                    stream.Dispose();

                throw;
            }
        }
Example #18
0
        public static ArchiveWriter Create(Stream stream, bool dispose)
        {
            try
            {
                var writer = new ArchiveWriter(stream, dispose);

                stream.Position = 0;
                stream.SetLength(ArchiveMetadataFormat.kHeaderLength);
                stream.Write(writer.PrepareHeader(), 0, ArchiveMetadataFormat.kHeaderLength);

                return writer;
            }
            catch
            {
                if (dispose && stream != null)
                    stream.Dispose();

                throw;
            }
        }
Example #19
0
    private bool VerifySetLengthException(System.IO.Stream serialStream, long value, Type expectedException)
    {
        bool retValue = true;

        try
        {
            serialStream.SetLength(value);

            Console.WriteLine("ERROR!!!: No Excpetion was thrown");
            retValue = false;
        }
        catch (System.Exception e)
        {
            if (e.GetType() != expectedException)
            {
                Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException);
                retValue = false;
            }
        }
        return(retValue);
    }
Example #20
0
        /*
         * ID3			Tag Identifier
         * 02 00		2 bytes Version information
         * xx			Tag flags
         * xx xx xx xx	Tag size excluding header as sync safe integer
         * {Frames}
         * [Padding]	included in tag size
         *
         * Note: Unsync is applied on tag level; compression, encryption, footer,
         *		 ExtendedHeader and experimental are not allowed.
         *
         */
        private static void EncodeID3v2_2Tag(Stream s, ID3v2Tag tag)
        {
            StringEncoder.WriteLatin1String(s, "ID3", 3);
            s.WriteByte(0x02);
            s.WriteByte(0x00);
            /* write flag byte */
            if ((tag.Flags & ID3v2TagFlags.Unsync) == ID3v2TagFlags.Unsync) {
                s.WriteByte((byte)0x80);
            } else {
                s.WriteByte((byte)0x00);
            }
            /* skip tag size */
            s.Position += 4L;

            WriteContentToStream(s, tag);
            s.SetLength(s.Length + ComputePaddingSize(s.Length, tag));

            /* update tag size */
            s.Position = 6L;
            NumberConverter.WriteInt(s.Length - 10L, s, 4, true);
        }
Example #21
0
		public void QueueDataBlock(Stream stream)
		{
			// Reset the stream position and keep track of the previous position.
			// The former position tells how much data we need to copy.
			stream.Flush();
			int l = (int)stream.Position;

			// Allocate unmanaged memory to store samples from stream
			var ptrData = Marshal.AllocHGlobal(l);

			// Populate a WAVEHDR with samples
			WAVEHDR hdr;
			using (var ums = new UnmanagedMemoryStream((byte*)ptrData.ToPointer(), l, l, FileAccess.ReadWrite))
			{
				stream.SetLength(l);
				stream.Position = 0;
				stream.CopyTo(ums, l);
				stream.Position = 0;
				ums.Position = 0;
				hdr = new WAVEHDR
				{
					BufferLength = (uint)l,
					Data = new IntPtr(ums.PositionPointer)
				};
			}

			// Copy WAVEHDR instance to unmanaged space
			var ptrHdr = Marshal.AllocHGlobal(sizeof(WAVEHDR));
			Marshal.StructureToPtr(hdr, ptrHdr, false);

			// Prepare the header and queue it
			MMRESULT result;
			if ((result = waveOutPrepareHeader(_ptrOutputDevice, ptrHdr, sizeof(WAVEHDR))) != MMRESULT.MMSYSERR_NOERROR)
				throw new ExternalException($"Function 'waveOutPrepareHeader' returned error code {result}");
			if ((result = waveOutWrite(_ptrOutputDevice, ptrHdr, sizeof(WAVEHDR))) != MMRESULT.MMSYSERR_NOERROR)
				throw new ExternalException($"Function 'waveOutWrite' returned error code {result}");

			// Increment queue size
			_queueSize++;
		}
        /// <summary> 
        /// Compress from the temp stream into the base stream
        /// </summary> 
        /// <remarks>Caller is responsible for correctly positioning source and sink stream pointers before calling.</remarks> 
        public void Compress(Stream source, Stream sink)
        { 
            // create deflate stream that can actually compress or decompress
            using (DeflateStream deflateStream = new DeflateStream(
                sink,                       // destination for compressed data
                CompressionMode.Compress,   // compress or decompress 
                true))                      // leave base stream open when the deflate stream is closed
            { 
                // persist to deflated stream from working stream 
                int bytesRead = 0;
                do 
                {
                    bytesRead = source.Read(Buffer, 0, Buffer.Length);
                    if (bytesRead > 0)
                        deflateStream.Write(Buffer, 0, bytesRead); 
                } while (bytesRead > 0);
            } 
 
            // truncate if necessary and possible
            if (sink.CanSeek) 
                sink.SetLength(sink.Position);
        }
Example #23
0
 /// <summary>
 /// 在流的指定位置插入一段数据。
 /// </summary>
 /// <param name="stream">目标流</param>
 /// <param name="position">插入位置</param>
 /// <param name="buffer">数据</param>
 /// <param name="count">数据大小</param>
 /// <returns>返回插入数据是否成功</returns>
 public static bool Insert(Stream stream, int position, byte[] data)
 {
     if (stream == null || data.Length <= 0 || position < 0 ||
         position > stream.Length)
         return false;
     int i = (int)stream.Length;
     byte[] vBuffer = new byte[0x1000];
     stream.SetLength(i + data.Length);
     int l;
     do
     {
         l = position + data.Length <= i - vBuffer.Length ?
             vBuffer.Length : i - position;
         stream.Position = i - l;
         stream.Read(vBuffer, 0, l);
         stream.Position = i - l + data.Length;
         stream.Write(vBuffer, 0, l);
         i -= l - data.Length;
     } while (l >= vBuffer.Length);
     stream.Position = position;
     stream.Write(data, 0, data.Length);
     return true;
 }
Example #24
0
        public override void WipeStream(Stream stream)
        {
            Random rdm = new Random();
            byte[] bytes;
            long maximumValue = 0;
            int divisor = 50;
            long steps = stream.Length / divisor;
            steps = (steps < 100) ? stream.Length : steps;

            int maxRounds = (Enhanced) ? 3 : 1;


            for (int round = 0; round < maxRounds; round++)
            {
                bytes = Enumerable.Repeat<byte>(0x00, (int)steps).ToArray();
                maximumValue = stream.Length - bytes.Length;
                while (stream.Position < maximumValue)
                    stream.Write(bytes, 0, bytes.Length);
                while (stream.Position < maximumValue)
                    stream.WriteByte(0x00);


                bytes = Enumerable.Repeat<byte>(0xFF, (int)steps).ToArray();
                while (stream.Position < maximumValue)
                    stream.Write(bytes, 0, bytes.Length);
                while (stream.Position < maximumValue)
                    stream.WriteByte(0x00);

                rdm.NextBytes(bytes);
                while (stream.Position < maximumValue)
                    stream.Write(bytes, 0, bytes.Length);
                while (stream.Position < maximumValue)
                    stream.WriteByte(0x00);
            }
            stream.SetLength(0);
        }
Example #25
0
 /// <summary>
 ///   Set the length of the underlying stream.  Be careful with this!
 /// </summary>
 ///
 /// <param name='value'>the length to set on the underlying stream.</param>
 public override void SetLength(long value)
 {
     _s.SetLength(value);
 }
Example #26
0
        // 替换文件某一部分
        // 注意,如果当前文件为UNICODE字符集,不要破坏文件开头的UNICODE方向标志
        // parameters:
        //        nStartOffs	被替换区间的开始偏移(以byte计算)
        //        nEndOffs	被替换区间的结束偏移(以byte计算) nEndOffs可以和nStartOffs重合,表示插入内容
        //        baNew		新的内容。如果想删除文件中一段内容,可以用刚构造的新CByteArray对象作为本参数。
        public static int Replace(Stream s,
            long nStartOffs,
            long nEndOffs,
            byte[] baNew)
        {
            long nFileLen;
            long nOldBytes;
            int nNewBytes;
            long nDelta = 0;
            byte[] baBuffer = null;
            int nMaxChunkSize = 4096;
            int nChunkSize;
            long nRightPartLen;
            long nHead;
            // BOOL bRet;
            int nReadBytes/*, nWriteBytes*/;

            // 检测开始与结束部位是否合法
            if (nStartOffs < 0)
            {
                throw (new Exception("nStartOffs不能小于0"));
            }
            if (nEndOffs < nStartOffs)
            {
                throw (new Exception("nStartOffs不能大于nEndOffs"));
            }
            nFileLen = s.Length;

            if (nEndOffs > nFileLen)
            {
                throw (new Exception("nEndOffs不能大于文件长度"));
            }

            // 计算被替换区间原来的长度
            nOldBytes = nEndOffs - nStartOffs;

            // 计算新长度
            nNewBytes = baNew.Length;

            if (nNewBytes != nOldBytes)
            { // 新旧长度不等,需要移动区间后面的文件内容

                // 根据增加还是减少长度,需要采取不同的移动策略
                // | prev | cur | trail |
                // | prev | cur + delta --> | trial | 先移右方向的块
                // | prev | cur - delta <-- | trial | 先移动左方向的块
                nDelta = nNewBytes - nOldBytes;
                if (nDelta > 0)
                {	// 整体向右移动, 从右面的块开始作
                    nRightPartLen = nFileLen - nStartOffs - nOldBytes;
                    nChunkSize = (int)Math.Min(nRightPartLen, nMaxChunkSize);
                    nHead = nFileLen - nChunkSize;
                    if (baBuffer == null || baBuffer.Length < nChunkSize)
                    {
                        baBuffer = new byte[nChunkSize];
                    }
                    // baBuffer.SetSize(nChunkSize);
                    for (; ; )
                    {
                        s.Seek(nHead, SeekOrigin.Begin);
                        //SetFilePointer(m_hFile,nHead,NULL,FILE_BEGIN);

                        nReadBytes = s.Read(baBuffer, 0, nChunkSize);
                        /*
                        bRet = ReadFile(m_hFile, baBuffer.GetData(), nChunkSize,
                            (LPDWORD)&nReadBytes, NULL);
                        if (bRet == FALSE)
                            goto ERROR1;
                        */

                        s.Seek(nHead + nDelta, SeekOrigin.Begin);
                        // SetFilePointer(m_hFile,nHead+nDelta,NULL,FILE_BEGIN);

                        s.Write(baBuffer, 0, nReadBytes);
                        /*
                        bRet = WriteFile(m_hFile, baBuffer.GetData(), nReadBytes,
                            (LPDWORD)&nWriteBytes, NULL);
                        if (bRet == FALSE)
                            goto ERROR1;
                        if (nWriteBytes != nReadBytes)
                        {
                            // 磁盘满
                            m_nErrNo = ERROR_DISK_FULL;
                            return -1;
                        }
                        */
                        // 移动全部完成
                        if (nHead <= nStartOffs + nOldBytes)	// < 是为了安全
                            break;
                        // 移动头位置
                        nHead -= nChunkSize;
                        if (nHead < nStartOffs + nOldBytes)
                        {
                            nChunkSize -= (int)(nStartOffs + nOldBytes - nHead);
                            nHead = nStartOffs + nOldBytes;
                        }

                    }
                }

                if (nDelta < 0)
                {	// 整体向左移动, 从左面的块开始作
                    nRightPartLen = nFileLen - nStartOffs - nOldBytes;
                    nChunkSize = (int)Math.Min(nRightPartLen, nMaxChunkSize);
                    if (baBuffer == null || baBuffer.Length < nChunkSize)
                    {
                        baBuffer = new byte[nChunkSize];
                    }

                    //baBuffer.SetSize(nChunkSize);
                    nHead = nStartOffs + nOldBytes;
                    for (; ; )
                    {
                        s.Seek(nHead, SeekOrigin.Begin);
                        // SetFilePointer(m_hFile,nHead,NULL,FILE_BEGIN);

                        nReadBytes = s.Read(baBuffer, 0, nChunkSize);
                        /*
                        bRet = ReadFile(m_hFile, baBuffer.GetData(), nChunkSize,
                            (LPDWORD)&nReadBytes, NULL);
                        if (bRet == FALSE)
                            goto ERROR1;
                        */

                        s.Seek(nHead + nDelta, SeekOrigin.Begin);
                        // SetFilePointer(m_hFile,nHead+nDelta,NULL,FILE_BEGIN);

                        s.Write(baBuffer, 0, nReadBytes);
                        /*
                        bRet = WriteFile(m_hFile, baBuffer.GetData(), nReadBytes,
                            (LPDWORD)&nWriteBytes, NULL);
                        if (bRet == FALSE)
                            goto ERROR1;
                        if (nWriteBytes != nReadBytes)
                        {
                            // 磁盘满
                            m_nErrNo = ERROR_DISK_FULL;
                            return -1;
                        }
                        */
                        // 移动全部完成
                        if (nHead + nChunkSize >= nFileLen)
                            break;
                        // 移动头位置
                        nHead += nChunkSize;
                        if (nHead + nChunkSize > nFileLen)
                        { // >是为了安全
                            nChunkSize -= (int)(nHead + nChunkSize - nFileLen);
                        }

                    }
                    // 截断文件(因为缩小了文件尺寸)
                    //ASSERT(nFileLen+nDelta>=0);
                    if (nFileLen + nDelta < 0)
                    {
                        throw (new Exception("nFileLen + nDelta < 0"));
                    }

                    s.SetLength(nFileLen + nDelta);
                    /*
                    SetFilePointer(m_hFile, nFileLen+nDelta, NULL, FILE_BEGIN);
                    SetEndOfFile(m_hFile);
                    */
                }

                //ASSERT(nDelta != 0);
                if (nDelta == 0)
                {
                    throw (new Exception("nDelta == 0"));
                }

            }

            // 将新内容写入

            if (nNewBytes != 0)
            {
                s.Seek(nStartOffs, SeekOrigin.Begin);
                //SetFilePointer(m_hFile,nStartOffs,NULL,FILE_BEGIN);

                s.Write(baNew, 0, nNewBytes);
                /*
                bRet = WriteFile(m_hFile, baNew.GetData(), nNewBytes,
                    (LPDWORD)&nWriteBytes, NULL);
                if (bRet == FALSE)
                    goto ERROR1;
                if (nWriteBytes != nNewBytes)
                {
                    // 磁盘满
                    m_nErrNo = ERROR_DISK_FULL;
                    return -1;
                }
                */
            }

            /*
            // 恢复写入前的文件指针,并且迫使缓冲区失效
            if (m_nPos > nFileLen + nDelta)
                m_nPos = nFileLen + nDelta;
            SetFilePointer(m_hFile, m_nPos, NULL, FILE_BEGIN);
            m_baCache.RemoveAll();
            m_bEOF = FALSE;
            return 0;
            ERROR1:
                m_nErrNo = GetLastError();
            return -1;
            */

            return 0;
        }
Example #27
0
        /*
         * ID3			Tag Identifier
         * 03 00		2 bytes Version information
         * xx			Tag flags
         * xx xx xx xx	Tag size excluding header but including extended header as sync safe integer
         * [Extended header]
         * {Frames}
         * [Padding]	included in tag size
         *
         * Note: Unsync is applied on tag level; footer is not allowed.
         *
         */
        private static void EncodeID3v2_3Tag(Stream s, ID3v2Tag tag)
        {
            long paddingLen;
            byte flags = 0;

            const long TagHeaderSize = 10L;
            const long ExtHeaderSizeWithCrc = 14L;
            const long ExtHeaderSizeWithoutCrc = 10L;

            /* generate flag byte */
            if ((tag.Flags & ID3v2TagFlags.Unsync) == ID3v2TagFlags.Unsync) {
                flags |= 0x80;
            }
            if (tag.ExtendedHeader != null) {
                flags |= 0x40;
            }
            if ((tag.Flags & ID3v2TagFlags.Experimental) == ID3v2TagFlags.Experimental) {
                flags |= 0x20;
            }

            /* write tag header */
            StringEncoder.WriteLatin1String(s, "ID3", 3);
            s.WriteByte(0x03);
            s.WriteByte(0x00);
            s.WriteByte(flags);

            /* skip size */
            s.Position += 4;

            if (tag.ExtendedHeader != null) {
                long crc;
                byte[] frameData = GetFrameRawData(tag);

                if ((tag.ExtendedHeader.Flags & ExtendedHeaderFlags.CrcPresent) == ExtendedHeaderFlags.CrcPresent) {
                    crc = Crc32.ComputeCrc(frameData);
                    paddingLen = ComputePaddingSize(frameData.Length + TagHeaderSize + ExtHeaderSizeWithCrc, tag);
                } else {
                    crc = -1L;
                    paddingLen = ComputePaddingSize(frameData.Length + TagHeaderSize + ExtHeaderSizeWithoutCrc, tag);
                }

                if ((tag.Flags & ID3v2TagFlags.Unsync) == ID3v2TagFlags.Unsync) {
                    UnsyncFilterStream unsyncFilterStream = new UnsyncFilterStream(s, UnsyncMode.Write, true);

                    EncodeID3v2_3ExtendedHeader(unsyncFilterStream, tag.ExtendedHeader, paddingLen, crc);
                    unsyncFilterStream.Write(frameData, 0, frameData.Length);
                    unsyncFilterStream.ApplyFinalization();

                } else {
                    EncodeID3v2_3ExtendedHeader(s, tag.ExtendedHeader, paddingLen, crc);
                    s.Write(frameData, 0, frameData.Length);
                }

            } else {
                /* no extended header */
                WriteContentToStream(s, tag);
                paddingLen = ComputePaddingSize(s.Length, tag);
            }

            /* update tag size */
            s.SetLength(s.Length + paddingLen);
            s.Position = 6;
            NumberConverter.WriteInt(s.Length - TagHeaderSize, s, 4, true);
        }
        public void Extract(Stream messageStream, Stream keyStream)
        {
            byte[] waveBuffer = new byte[bytesPerSample];
            byte message, bit, waveByte;
            int messageLength = 0;
            int keyByte;

            while( (messageLength==0 || messageStream.Length<messageLength) ){

                message = 0;

                for(int bitIndex=0; bitIndex<8; bitIndex++){

                    keyByte = GetKeyValue(keyStream);

                    for(int n=0; n<keyByte-1; n++)
                    {

                        sourceStream.Read(waveBuffer, 0, waveBuffer.Length);
                    }
                    sourceStream.Read(waveBuffer, 0, waveBuffer.Length);
                    waveByte = waveBuffer[bytesPerSample-1];

                    bit = (byte)(((waveByte % 2) == 0) ? 0 : 1);

                    message += (byte)(bit << bitIndex);
                }

                messageStream.WriteByte(message);

                if(messageLength==0 && messageStream.Length==4)
                {

                    messageStream.Seek(0, SeekOrigin.Begin);
                    messageLength = new BinaryReader(messageStream).ReadInt32();
                    messageStream.Seek(0, SeekOrigin.Begin);
                    messageStream.SetLength(0);
                }
            }
        }
Example #29
0
 /// <summary>
 /// Saves the composed Zip to the stream
 /// </summary>
 /// <param name="stream"></param>
 public void Save(Stream stream) {
     UpdateEndOfCentralDirectory();
     stream.SetLength(stream.Position + this.Length);
     stream.Write(_stream_locdir.GetBuffer(), 0, (int)_stream_locdir.Length);
     stream.Write(_stream_centdir.GetBuffer(), 0, (int)_stream_centdir.Length);
     stream.Write(_stream_eocd.GetBuffer(), 0, (int)_stream_eocd.Length);
 }
Example #30
0
 public void Clear(
     )
 {
     stream.SetLength(0);
 }
Example #31
0
        /// <summary>
        /// Close the file that the stream refers to
        /// </summary>
        public void Close()
        {
            // If the stream is already closed, then just return
            if (_zipOpen == ZipOpenType.Closed)
            {
                return;
            }

            // If the stream is opened for read, close it
            if (_zipOpen == ZipOpenType.OpenRead)
            {
                Dispose();
                _zipOpen = ZipOpenType.Closed;
                return;
            }

            // Now, the only other choice is open for writing so we check everything is correct
            _zip64 = false;
            bool torrentZip = true;

            // Check the central directory
            _centerDirStart = (ulong)_zipstream.Position;
            if (_centerDirStart >= 0xffffffff)
            {
                _zip64 = true;
            }

            // Now loop through and add all of the central directory entries
            foreach (ZipFileEntry zfe in _entries)
            {
                zfe.WriteCentralDirectory(_zipstream);
                _zip64     |= zfe.Zip64;
                torrentZip &= zfe.TorrentZip;
            }

            _centerDirSize = (ulong)_zipstream.Position - _centerDirStart;

            // Then get the central directory hash
            OptimizedCRC ocrc = new OptimizedCRC();

            byte[] buffer          = new byte[_centerDirSize];
            long   currentPosition = _zipstream.Position;

            _zipstream.Position = (long)_centerDirStart;

            // Then read in the central directory and hash
            BinaryReader br = new BinaryReader(_zipstream);

            buffer = br.ReadBytes((int)_centerDirSize);
            ocrc.Update(buffer, 0, (int)_centerDirSize);
            string calculatedCrc = ocrc.Value.ToString("X8");

            // Finally get back to the original position
            _zipstream.Position = currentPosition;

            // Now set more of the information
            _fileComment = (torrentZip ? Encoding.ASCII.GetBytes(("TORRENTZIPPED-" + calculatedCrc).ToCharArray()) : new byte[0]);
            _zipStatus   = (torrentZip ? ZipStatus.TorrentZip : ZipStatus.None);

            // If we have a Zip64 archive, write the correct information
            if (_zip64)
            {
                _endOfCenterDir64 = (ulong)_zipstream.Position;
                WriteZip64EndOfCentralDir();
                WriteZip64EndOfCentralDirectoryLocator();
            }

            // Now write out the end of the central directory
            WriteEndOfCentralDir();

            // Finally, close and dispose of the stream
            _zipstream.SetLength(_zipstream.Position);
            _zipstream.Flush();
            _zipstream.Close();
            _zipstream.Dispose();

            // Get the new file information
            _zipFileInfo = new FileInfo(_zipFileInfo.FullName);

            // And set the stream to closed
            _zipOpen = ZipOpenType.Closed;
        }
 public override void SetLength(long value)
 {
     _innerStream.SetLength(value);
 }
Example #33
0
        static int PrepareCacheFile(
            string strCacheDir,
            string strLogFileName,
            long lServerFileSize,
            out bool bCacheFileExist,
            out Stream stream,
            out string strError)
        {
            strError = "";
            stream = null;
            // 观察本地缓存文件是否存在
            bCacheFileExist = false;
            XmlDocument metadata_dom = new XmlDocument();

            string strCacheFilename = PathUtil.MergePath(strCacheDir, strLogFileName);
            string strCacheMetaDataFilename = PathUtil.MergePath(strCacheDir, strLogFileName + ".meta");

            if (File.Exists(strCacheFilename) == true
                && File.Exists(strCacheMetaDataFilename) == true)
            {
                bCacheFileExist = true;

                // 观察metadata
                try
                {
                    metadata_dom.Load(strCacheMetaDataFilename);
                }
                catch (FileNotFoundException)
                {
                    bCacheFileExist = false;    // 虽然数据文件存在,也需要重新获取
                }
                catch (Exception ex)
                {
                    strError = "装载metadata文件 '" + strCacheMetaDataFilename + "' 时出错: " + ex.Message;
                    return -1;
                }

                // 对比文件尺寸
                string strFileSize = DomUtil.GetAttr(metadata_dom.DocumentElement, "serverFileSize");
                if (string.IsNullOrEmpty(strFileSize) == true)
                {
                    strError = "metadata中缺乏fileSize属性";
                    return -1;
                }
                long lTempFileSize = 0;
                if (Int64.TryParse(strFileSize, out lTempFileSize) == false)
                {
                    strError = "metadata中缺乏fileSize属性值 '" + strFileSize + "' 格式错误";
                    return -1;
                }

                if (lTempFileSize != lServerFileSize)
                    bCacheFileExist = false;

            }
            // 如果文件存在,就打开,如果文件不存在,就创建一个新的
            stream = File.Open(
strCacheFilename,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.ReadWrite);

            if (bCacheFileExist == false)
                stream.SetLength(0);

            return 0;
        }
Example #34
0
 public override void SetLength(long length)
 {
     lock (_stream)
         _stream.SetLength(length);
 }
Example #35
0
 /// <summary>
 /// 当在派生类中重写时,设置当前流的长度。
 /// </summary>
 /// <param name="value">所需的当前流的长度(以字节表示)。</param><exception cref="T:System.IO.IOException">发生 I/O 错误。</exception><exception cref="T:System.NotSupportedException">流不支持写入和查找,例如在流通过管道或控制台输出构造的情况下即为如此。</exception><exception cref="T:System.ObjectDisposedException">在流关闭后调用方法。</exception>
 public override void SetLength(long value)
 {
     _innerStream.SetLength(value);
     OnPositionChanged();
 }
Example #36
0
 public override void SetLength(System.Int64 value)
 {
     _stream.SetLength(value);
     nomoreinput = false;
 }
Example #37
0
        /*
         * ID3			Tag identifier
         * 04 00		2 bytes version
         * xx			Tag flags
         * xx xx xx xx	Tag size excluding header and footer as syncsafe int
         * [Extended header]
         * {Frames}
         * [Padding]
         * [Footer]
         */
        private static void EncodeID3v2_4Tag(Stream s, ID3v2Tag tag)
        {
            byte flagByte = 0;
            long paddingLen, size;

            const long TagHeaderSize = 10L;

            if ((tag.Flags & ID3v2TagFlags.Unsync) == ID3v2TagFlags.Unsync) {
                flagByte |= 0x80;
            }
            if (tag.ExtendedHeader != null) {
                flagByte |= 0x40;
            }
            if ((tag.Flags & ID3v2TagFlags.Experimental) == ID3v2TagFlags.Experimental) {
                flagByte |= 0x20;
            }
            if ((tag.Flags & ID3v2TagFlags.Footer) == ID3v2TagFlags.Footer) {
                flagByte |= 0x10;
            }

            StringEncoder.WriteLatin1String(s, "ID3", 3);
            s.WriteByte(0x04);
            s.WriteByte(0x00);
            s.WriteByte(flagByte);

            /* skip size */
            s.Position += 4;

            if (tag.ExtendedHeader != null) {
                byte[] frameData = GetFrameRawData(tag);
                long crc = -1L;

                if ((tag.ExtendedHeader.Flags & ExtendedHeaderFlags.CrcPresent) == ExtendedHeaderFlags.CrcPresent) {
                    /* CRC is calculated on frame data and padding */
                    Crc32 crcCalc = new Crc32();
                    crcCalc.UpdateCrc(frameData);
                    crcCalc.UpdateCrcWithZero(ComputePaddingSize(frameData.Length + TagHeaderSize, tag));
                    crc = crcCalc.Crc;
                }
                EncodeID3v2_4ExtendedHeader(s, tag.ExtendedHeader, crc);
                s.Write(frameData, 0, frameData.Length);

            } else {
                foreach (Frame f in tag.Frames) {
                    FrameEncoder.EncodeFrame(s, f, tag);
                }
            }

            paddingLen = ComputePaddingSize(s.Length, tag);
            s.SetLength(s.Length + paddingLen);
            size = s.Length - TagHeaderSize;

            if ((tag.Flags & ID3v2TagFlags.Footer) == ID3v2TagFlags.Footer) {
                s.Position = s.Length - 1L;
                StringEncoder.WriteLatin1String(s, "3DI", 3);
                s.WriteByte(0x04);
                s.WriteByte(0x00);
                s.WriteByte(flagByte);
                NumberConverter.WriteInt(size, s, 4, true);
            }

            s.Position = 6L;
            NumberConverter.WriteInt(size, s, 4, true);
        }
Example #38
0
        public string Publish()
        {
            string html = Request["html"];
            string name = Request["name"];
            string att  = Request["att"];
            string id   = Request["id"];

            Guid gid;

            if (!id.IsGuid(out gid) || name.IsNullOrEmpty() || att.IsNullOrEmpty() || html.IsNullOrEmpty())
            {
                return("参数错误!");
            }
            RoadFlow.Platform.WorkFlowForm WFF = new RoadFlow.Platform.WorkFlowForm();

            RoadFlow.Data.Model.WorkFlowForm wff = WFF.Get(gid);
            if (wff == null)
            {
                return("未找到表单!");
            }

            string fileName = id + ".cshtml";

            System.Text.StringBuilder serverScript = new System.Text.StringBuilder("@{\r\n");
            var attrJSON = LitJson.JsonMapper.ToObject(att);

            serverScript.Append("\tstring FlowID = Request.QueryString[\"flowid\"];\r\n");
            serverScript.Append("\tstring StepID = Request.QueryString[\"stepid\"];\r\n");
            serverScript.Append("\tstring GroupID = Request.QueryString[\"groupid\"];\r\n");
            serverScript.Append("\tstring TaskID = Request.QueryString[\"taskid\"];\r\n");
            serverScript.Append("\tstring InstanceID = Request.QueryString[\"instanceid\"];\r\n");
            serverScript.Append("\tstring DisplayModel = Request.QueryString[\"display\"] ?? \"0\";\r\n");
            serverScript.AppendFormat("\tstring DBConnID = \"{0}\";\r\n", attrJSON["dbconn"].ToString());
            serverScript.AppendFormat("\tstring DBTable = \"{0}\";\r\n", attrJSON["dbtable"].ToString());
            serverScript.AppendFormat("\tstring DBTablePK = \"{0}\";\r\n", attrJSON["dbtablepk"].ToString());
            serverScript.AppendFormat("\tstring DBTableTitle = \"{0}\";\r\n", attrJSON["dbtabletitle"].ToString());

            serverScript.Append("\tRoadFlow.Platform.Dictionary BDictionary = new RoadFlow.Platform.Dictionary();\r\n");
            serverScript.Append("\tRoadFlow.Platform.WorkFlow BWorkFlow = new RoadFlow.Platform.WorkFlow();\r\n");
            serverScript.Append("\tRoadFlow.Platform.WorkFlowTask BWorkFlowTask = new RoadFlow.Platform.WorkFlowTask();\r\n");
            serverScript.Append("\tstring fieldStatus = BWorkFlow.GetFieldStatus(FlowID, StepID);\r\n");
            serverScript.Append("\tLitJson.JsonData initData = BWorkFlow.GetFormData(DBConnID, DBTable, DBTablePK, InstanceID, fieldStatus);\r\n");
            serverScript.Append("\tstring TaskTitle = BWorkFlow.GetFromFieldData(initData, DBTable, DBTableTitle);\r\n");

            serverScript.Append("}\r\n");
            serverScript.Append("<link href=\"~/Scripts/FlowRun/Forms/flowform.css\" rel=\"stylesheet\" type=\"text/css\" />\r\n");
            serverScript.Append("<script src=\"~/Scripts/FlowRun/Forms/common.js\" type=\"text/javascript\" ></script>\r\n");

            if (attrJSON.ContainsKey("hasEditor") && "1" == attrJSON["hasEditor"].ToString())
            {
                serverScript.Append("<script src=\"~/Scripts/Ueditor/ueditor.config.js\" type=\"text/javascript\" ></script>\r\n");
                serverScript.Append("<script src=\"~/Scripts/Ueditor/ueditor.all.min.js\" type=\"text/javascript\" ></script>\r\n");
                serverScript.Append("<script src=\"~/Scripts/Ueditor/lang/zh-cn/zh-cn.js\" type=\"text/javascript\" ></script>\r\n");
                serverScript.Append("<input type=\"hidden\" id=\"Form_HasUEditor\" name=\"Form_HasUEditor\" value=\"1\" />\r\n");
            }
            string validatePropType = attrJSON.ContainsKey("validatealerttype") ? attrJSON["validatealerttype"].ToString() : "2";

            serverScript.Append("<input type=\"hidden\" id=\"Form_ValidateAlertType\" name=\"Form_ValidateAlertType\" value=\"" + validatePropType + "\" />\r\n");
            if (attrJSON.ContainsKey("autotitle") && attrJSON["autotitle"].ToString().ToLower() == "true")
            {
                serverScript.AppendFormat("<input type=\"hidden\" id=\"{0}\" name=\"{0}\" value=\"{1}\" />\r\n",
                                          string.Concat(attrJSON["dbtable"].ToString(), ".", attrJSON["dbtabletitle"].ToString()),
                                          "@(TaskTitle.IsNullOrEmpty() ? BWorkFlow.GetAutoTaskTitle(FlowID, StepID, Request.QueryString[\"groupid\"]) : TaskTitle)"
                                          );
            }
            serverScript.AppendFormat("<input type=\"hidden\" id=\"Form_TitleField\" name=\"Form_TitleField\" value=\"{0}\" />\r\n", string.Concat(attrJSON["dbtable"].ToString(), ".", attrJSON["dbtabletitle"].ToString()));
            //serverScript.AppendFormat("<input type=\"hidden\" id=\"Form_Name\" name=\"Form_Name\" value=\"{0}\" />\r\n", attrJSON["name"].ToString());
            serverScript.AppendFormat("<input type=\"hidden\" id=\"Form_DBConnID\" name=\"Form_DBConnID\" value=\"{0}\" />\r\n", attrJSON["dbconn"].ToString());
            serverScript.AppendFormat("<input type=\"hidden\" id=\"Form_DBTable\" name=\"Form_DBTable\" value=\"{0}\" />\r\n", attrJSON["dbtable"].ToString());
            serverScript.AppendFormat("<input type=\"hidden\" id=\"Form_DBTablePk\" name=\"Form_DBTablePk\" value=\"{0}\" />\r\n", attrJSON["dbtablepk"].ToString());
            serverScript.AppendFormat("<input type=\"hidden\" id=\"Form_DBTableTitle\" name=\"Form_DBTableTitle\" value=\"{0}\" />\r\n", attrJSON["dbtabletitle"].ToString());
            serverScript.AppendFormat("<input type=\"hidden\" id=\"Form_AutoSaveData\" name=\"Form_AutoSaveData\" value=\"{0}\" />\r\n", "1");
            serverScript.Append("<script type=\"text/javascript\">\r\n");
            serverScript.Append("\tvar initData = @Html.Raw(BWorkFlow.GetFormDataJsonString(initData));\r\n");
            serverScript.Append("\tvar fieldStatus = @Html.Raw(fieldStatus);\r\n");
            serverScript.Append("\tvar displayModel = '@DisplayModel';\r\n");
            serverScript.Append("\t$(window).load(function (){\r\n");
            serverScript.AppendFormat("\t\tformrun.initData(initData, \"{0}\", fieldStatus, displayModel);\r\n", attrJSON["dbtable"].ToString());
            serverScript.Append("\t});\r\n");
            serverScript.Append("</script>\r\n");


            string file = Server.MapPath("~/Views/WorkFlowFormDesigner/Forms/" + fileName);

            System.IO.Stream stream = System.IO.File.Open(file, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
            stream.SetLength(0);

            StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.UTF8);

            sw.Write(serverScript.ToString());
            html = HttpUtility.HtmlDecode(html);
            html = html.Replace("+", "%2B");
            sw.Write(HttpUtility.UrlDecode(html));
            sw.Close();
            stream.Close();


            string attr    = wff.Attribute;
            string appType = LitJson.JsonMapper.ToObject(attr)["apptype"].ToString();

            RoadFlow.Platform.AppLibraryBLL App = new RoadFlow.Platform.AppLibraryBLL();
            var  app   = App.GetByCode(id);
            bool isAdd = false;

            if (app == null)
            {
                app      = new RoadFlow.Data.Model.AppLibraryModel();
                app.ID   = Guid.NewGuid();
                app.Code = id;
                isAdd    = true;
            }
            app.Address  = "/Views/WorkFlowFormDesigner/Forms/" + fileName;
            app.Note     = "流程表单";
            app.OpenMode = 0;
            app.Params   = "";
            app.Title    = name.Trim();
            app.Type     = appType.IsGuid() ? appType.Convert <Guid>() : new RoadFlow.Platform.DictionaryBLL().GetIDByCode("FormTypes");
            if (isAdd)
            {
                App.Add(app);
            }
            else
            {
                App.Update(app);
            }

            RoadFlow.Platform.Log.Add("发布了流程表单", app.Serialize() + "内容:" + html, RoadFlow.Platform.Log.Types.流程相关);
            wff.Status = 1;
            WFF.Update(wff);
            return("发布成功!");
        }
Example #39
0
        /// <summary>
        /// Initializes a stream as a raw disk image.
        /// </summary>
        /// <param name="stream">The stream to initialize.</param>
        /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param>
        /// <param name="capacity">The desired capacity of the new disk</param>
        /// <param name="geometry">The geometry of the new disk</param>
        /// <returns>An object that accesses the stream as a raw disk image</returns>
        public static DiskImageFile Initialize(Stream stream, Ownership ownsStream, long capacity, Geometry geometry)
        {
            stream.SetLength(Utilities.RoundUp(capacity, Sizes.Sector));

            // Wipe any pre-existing master boot record / BPB
            stream.Position = 0;
            stream.Write(new byte[Sizes.Sector], 0, Sizes.Sector);
            stream.Position = 0;

            return new DiskImageFile(stream, ownsStream, geometry);
        }
Example #40
0
 public override void SetLength(long value)
 {
     stream.SetLength(value);
 }
Example #41
0
        /// <summary>
        /// Creates a formatted hard disk partition in a stream.
        /// </summary>
        /// <param name="stream">The stream to write the new file system to</param>
        /// <param name="label">The volume label for the partition (or null)</param>
        /// <param name="diskGeometry">The geometry of the disk containing the partition</param>
        /// <param name="firstSector">The starting sector number of this partition (hide's sectors in other partitions)</param>
        /// <param name="sectorCount">The number of sectors in this partition</param>
        /// <param name="reservedSectors">The number of reserved sectors at the start of the partition</param>
        /// <returns>An object that provides access to the newly created partition file system</returns>
        public static FatFileSystem FormatPartition(
            Stream stream,
            string label,
            Geometry diskGeometry,
            int firstSector,
            int sectorCount,
            short reservedSectors)
        {
            long pos = stream.Position;

            long ticks = DateTime.UtcNow.Ticks;
            uint volId = (uint)((ticks & 0xFFFF) | (ticks >> 32));

            byte sectorsPerCluster;
            FatType fatType;
            ushort maxRootEntries;

            /*
             * Write the BIOS Parameter Block (BPB) - a single sector
             */

            byte[] bpb = new byte[512];
            if (sectorCount <= 8400)
            {
                throw new ArgumentException("Requested size is too small for a partition");
            }
            else if (sectorCount < 1024 * 1024)
            {
                fatType = FatType.Fat16;
                maxRootEntries = 512;
                if (sectorCount <= 32680)
                {
                    sectorsPerCluster = 2;
                }
                else if (sectorCount <= 262144)
                {
                    sectorsPerCluster = 4;
                }
                else if (sectorCount <= 524288)
                {
                    sectorsPerCluster = 8;
                }
                else
                {
                    sectorsPerCluster = 16;
                }

                if (reservedSectors < 1)
                {
                    reservedSectors = 1;
                }
            }
            else
            {
                fatType = FatType.Fat32;
                maxRootEntries = 0;
                if (sectorCount <= 532480)
                {
                    sectorsPerCluster = 1;
                }
                else if (sectorCount <= 16777216)
                {
                    sectorsPerCluster = 8;
                }
                else if (sectorCount <= 33554432)
                {
                    sectorsPerCluster = 16;
                }
                else if (sectorCount <= 67108864)
                {
                    sectorsPerCluster = 32;
                }
                else
                {
                    sectorsPerCluster = 64;
                }

                if (reservedSectors < 32)
                {
                    reservedSectors = 32;
                }
            }

            WriteBPB(bpb, (uint)sectorCount, fatType, maxRootEntries, (uint)firstSector, (ushort)reservedSectors, sectorsPerCluster, diskGeometry, false, volId, label);
            stream.Write(bpb, 0, bpb.Length);

            /*
             * Skip the reserved sectors
             */

            stream.Position = pos + (((ushort)reservedSectors) * Utilities.SectorSize);

            /*
             * Write both FAT copies
             */

            byte[] fat = new byte[CalcFatSize((uint)sectorCount, fatType, sectorsPerCluster) * Utilities.SectorSize];
            FatBuffer fatBuffer = new FatBuffer(fatType, fat);
            fatBuffer.SetNext(0, 0xFFFFFFF8);
            fatBuffer.SetEndOfChain(1);
            if (fatType >= FatType.Fat32)
            {
                // Mark cluster 2 as End-of-chain (i.e. root directory
                // is a single cluster in length)
                fatBuffer.SetEndOfChain(2);
            }

            stream.Write(fat, 0, fat.Length);
            stream.Write(fat, 0, fat.Length);

            /*
             * Write the (empty) root directory
             */

            uint rootDirSectors;
            if (fatType < FatType.Fat32)
            {
                rootDirSectors = (uint)(((maxRootEntries * 32) + Utilities.SectorSize - 1) / Utilities.SectorSize);
            }
            else
            {
                rootDirSectors = sectorsPerCluster;
            }

            byte[] rootDir = new byte[rootDirSectors * Utilities.SectorSize];
            stream.Write(rootDir, 0, rootDir.Length);

            /*
             * Make sure the stream is at least as large as the partition requires.
             */

            if (stream.Length < pos + (sectorCount * Utilities.SectorSize))
            {
                stream.SetLength(pos + (sectorCount * Utilities.SectorSize));
            }

            /*
             * Give the caller access to the new file system
             */

            stream.Position = pos;
            return new FatFileSystem(stream);
        }
Example #42
0
        private async Task <FileStreamBase> OpenAsync(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
        {
            // When trying to open the root directory, we need to throw an Access Denied
            if (PathHelpers.GetRootLength(fullPath) == fullPath.Length)
            {
                throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_ACCESS_DENIED, fullPath);
            }

            // Win32 CreateFile returns ERROR_PATH_NOT_FOUND when given a path that ends with '\'
            if (PathHelpers.EndsInDirectorySeparator(fullPath))
            {
                throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_PATH_NOT_FOUND, fullPath);
            }

            StorageFile file = null;

            // FileMode
            if (mode == FileMode.Open || mode == FileMode.Truncate)
            {
                file = await StorageFile.GetFileFromPathAsync(fullPath).TranslateWinRTTask(fullPath);
            }
            else
            {
                CreationCollisionOption collisionOptions;

                switch (mode)
                {
                case FileMode.Create:
                    collisionOptions = CreationCollisionOption.ReplaceExisting;
                    break;

                case FileMode.CreateNew:
                    collisionOptions = CreationCollisionOption.FailIfExists;
                    break;

                case FileMode.Append:
                case FileMode.OpenOrCreate:
                default:
                    collisionOptions = CreationCollisionOption.OpenIfExists;
                    break;
                }

                string directoryPath, fileName;
                PathHelpers.SplitDirectoryFile(fullPath, out directoryPath, out fileName);

                StorageFolder directory = await StorageFolder.GetFolderFromPathAsync(directoryPath).TranslateWinRTTask(directoryPath, isDirectory: true);

                file = await directory.CreateFileAsync(fileName, collisionOptions).TranslateWinRTTask(fullPath);
            }

            // FileAccess: WinRT doesn't support FileAccessMode.Write so we upgrade to ReadWrite
            FileAccessMode accessMode = ((access & FileAccess.Write) != 0) ? FileAccessMode.ReadWrite : FileAccessMode.Read;

            // FileShare: cannot translate StorageFile uses a different sharing model (oplocks) that is controlled via FileAccessMode

            // FileOptions: ignore most values of FileOptions as they are hints and are not supported by WinRT.
            // FileOptions.Encrypted is not a hint, and not supported by WinRT, but there is precedent for ignoring this (FAT).
            // FileOptions.DeleteOnClose should result in an UnauthorizedAccessException when
            //   opening a file that can only be read, but we cannot safely reproduce that behavior
            //   in WinRT without actually deleting the file.
            //   Instead the failure will occur in the finalizer for WinRTFileStream and be ignored.

            // open our stream
            Stream stream = (await file.OpenAsync(accessMode).TranslateWinRTTask(fullPath)).AsStream(bufferSize);

            if (mode == FileMode.Append)
            {
                // seek to end.
                stream.Seek(0, SeekOrigin.End);
            }
            else if (mode == FileMode.Truncate)
            {
                // truncate stream to 0
                stream.SetLength(0);
            }

            return(new WinRTFileStream(stream, file, access, options, parent));
        }
 public override void SetLength(System.Int64 value)
 {
     _stream.SetLength(value);
 }
Example #44
0
 public override void SetLength(long value)
 {
     inner.SetLength(value);
 }