System.IO.FileStream.Seek(long, System.IO.SeekOrigin)

Here are the examples of the csharp api System.IO.FileStream.Seek(long, System.IO.SeekOrigin) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

745 Examples 7

19 View Source File : SteamBotController.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

static void OnMachineAuth(SteamUser.UpdateMachineAuthCallback callback)
        {
            Console.WriteLine("Updating sentryfile...");

            // write out our sentry file
            // ideally we'd want to write to the filename specified in the callback
            // but then this sample would require more code to find the correct sentry file to read during logon
            // for the sake of simplicity, we'll just use "sentry.bin"

            int fileSize;
            byte[] sentryHash;
            using (var fs = File.Open("sentry.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                fs.Seek(callback.Offset, SeekOrigin.Begin);
                fs.Write(callback.Data, 0, callback.BytesToWrite);
                fileSize = (int)fs.Length;

                fs.Seek(0, SeekOrigin.Begin);
                using (var sha = SHA1.Create())
                {
                    sentryHash = sha.ComputeHash(fs);
                }
            }

            // inform the steam servers that we're accepting this sentry file
            steamUser.SendMachineAuthResponse(new SteamUser.MachineAuthDetails
            {
                JobID = callback.JobID,

                FileName = callback.FileName,

                BytesWritten = callback.BytesToWrite,
                FileSize = fileSize,
                Offset = callback.Offset,

                Result = EResult.OK,
                LastError = 0,

                OneTimePreplacedword = callback.OneTimePreplacedword,

                SentryFileHash = sentryHash,
            });

            Console.WriteLine("Done!");
        }

19 View Source File : SteamBotController.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

static void OnMachineAuth(SteamUser.UpdateMachineAuthCallback callback)
        {
            Console.WriteLine("Updating sentryfile...");

            // write out our sentry file
            // ideally we'd want to write to the filename specified in the callback
            // but then this sample would require more code to find the correct sentry file to read during logon
            // for the sake of simplicity, we'll just use "sentry.bin"

            int fileSize;
            byte[] sentryHash;
            using (var fs = File.Open("sentry.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                fs.Seek(callback.Offset, SeekOrigin.Begin);
                fs.Write(callback.Data, 0, callback.BytesToWrite);
                fileSize = (int)fs.Length;

                fs.Seek(0, SeekOrigin.Begin);
                using (var sha = SHA1.Create())
                {
                    sentryHash = sha.ComputeHash(fs);
                }
            }

            // inform the steam servers that we're accepting this sentry file
            steamUser.SendMachineAuthResponse(new SteamUser.MachineAuthDetails
            {
                JobID = callback.JobID,

                FileName = callback.FileName,

                BytesWritten = callback.BytesToWrite,
                FileSize = fileSize,
                Offset = callback.Offset,

                Result = EResult.OK,
                LastError = 0,

                OneTimePreplacedword = callback.OneTimePreplacedword,

                SentryFileHash = sentryHash,
            });

            Console.WriteLine("Done!");
        }

19 View Source File : DownloadFile.cs
License : MIT License
Project Creator : 404Lcc

public bool Downloading()
        {
            if (File.Exists(downloadData.path))
            {
                currentSize = downloadData.size;
                return true;
            }
            long position = 0;
            string tempPath = downloadData.path + ".temp";
            if (File.Exists(tempPath))
            {
                using (FileStream fileStream = new FileStream(tempPath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                {
                    position = fileStream.Length;
                    fileStream.Seek(position, SeekOrigin.Current);
                    if (position == downloadData.size)
                    {
                        if (File.Exists(downloadData.path))
                        {
                            File.Delete(downloadData.path);
                        }
                        File.Move(tempPath, downloadData.path);
                        currentSize = position;
                        return true;
                    }
                }
            }
            else
            {
                PathUtil.GetPath(PathType.PersistentDataPath, Path.GetDirectoryName(downloadData.path));
                using (FileStream fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                {
                    HttpWebRequest httpWebRequest = null;
                    HttpWebResponse httpWebResponse = null;
                    try
                    {
                        httpWebRequest = (HttpWebRequest)WebRequest.Create(downloadData.url);
                        httpWebRequest.ReadWriteTimeout = readWriteTimeout;
                        httpWebRequest.Timeout = timeout;
                        if (position > 0)
                        {
                            httpWebRequest.AddRange((int)position);
                        }
                        httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                        using (Stream stream = httpWebResponse.GetResponseStream())
                        {
                            stream.ReadTimeout = timeout;
                            long currentSize = position;
                            byte[] bytes = new byte[fileReadLength];
                            int readSize = stream.Read(bytes, 0, fileReadLength);
                            while (readSize > 0)
                            {
                                fileStream.Write(bytes, 0, readSize);
                                currentSize += readSize;
                                if (currentSize == downloadData.size)
                                {
                                    if (File.Exists(downloadData.path))
                                    {
                                        File.Delete(downloadData.path);
                                    }
                                    File.Move(tempPath, downloadData.path);
                                }
                                this.currentSize = currentSize;
                                readSize = stream.Read(bytes, 0, fileReadLength);
                            }
                        }
                    }
                    catch
                    {
                        if (File.Exists(tempPath))
                        {
                            File.Delete(tempPath);
                        }
                        if (File.Exists(downloadData.path))
                        {
                            File.Delete(downloadData.path);
                        }
                        state = DownloadState.Error;
                        error = "文件下载失败";
                    }
                    finally
                    {
                        if (httpWebRequest != null)
                        {
                            httpWebRequest.Abort();
                            httpWebRequest = null;
                        }
                        if (httpWebResponse != null)
                        {
                            httpWebResponse.Dispose();
                            httpWebResponse = null;
                        }
                    }
                }
            }
            if (state == DownloadState.Error)
            {
                return false;
            }
            return true;
        }

19 View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio

private void DownloadFileCheck()
                {
                    var tmpFileName = m_HttpDownloadInfo.SavePath +"."+ m_HttpDownloadInfo.TempFileExtension;
                    if (File.Exists(tmpFileName))
                    {
                        m_FileStream = File.OpenWrite(tmpFileName);
                        m_Position = m_FileStream.Length;
                        m_FileStream.Seek(m_Position, SeekOrigin.Current);
                    }
                    else
                    {
                        m_FileStream = new FileStream(tmpFileName, FileMode.Create);
                        m_Position = 0L;
                    }
                }

19 View Source File : RecordStream.cs
License : MIT License
Project Creator : a1q123456

protected override async void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (!_disposed)
            {
                _disposed = true;
                if (_recordFileData != null)
                {
                    try
                    {
                        var filePath = _recordFileData.Name;
                        using (var recordFile = new FileStream(filePath.Substring(0, filePath.Length - 5) + ".flv", FileMode.OpenOrCreate))
                        {
                            recordFile.SetLength(0);
                            recordFile.Seek(0, SeekOrigin.Begin);
                            await recordFile.WriteAsync(FlvMuxer.MultiplexFlvHeader(true, true));
                            var metaData = _metaData.Data[1] as Dictionary<string, object>;
                            metaData["duration"] = ((double)_currentTimestamp) / 1000;
                            metaData["keyframes"] = _keyframes;
                            _metaData.MessageHeader.MessageLength = 0;
                            var dataTagLen = FlvMuxer.MultiplexFlv(_metaData).Length;

                            var offset = recordFile.Position + dataTagLen;
                            for (int i = 0; i < _keyframeFilePositions.Count; i++)
                            {
                                _keyframeFilePositions[i] = (double)_keyframeFilePositions[i] + offset;
                            }

                            await recordFile.WriteAsync(FlvMuxer.MultiplexFlv(_metaData));
                            _recordFileData.Seek(0, SeekOrigin.Begin);
                            await _recordFileData.CopyToAsync(recordFile);
                            _recordFileData.Dispose();
                            File.Delete(filePath);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
                _recordFile?.Dispose();
            }
        }

19 View Source File : RecordStream.cs
License : MIT License
Project Creator : a1q123456

private async Task SeekAndPlay(double milliSeconds, CancellationToken ct)
        {
            await _playLock.WaitAsync();
            Interlocked.Exchange(ref _playing, 1);
            try
            {

                _recordFile.Seek(9, SeekOrigin.Begin);
                FlvDemuxer.SeekNoLock(milliSeconds, _metaData == null ? null : _metaData.Data[2] as Dictionary<string, object>, ct);
                await StartPlayNoLock(ct);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                Interlocked.Exchange(ref _playing, 0);
                _playLock.Release();
            }
        }

19 View Source File : WebSocketPlayController.cs
License : MIT License
Project Creator : a1q123456

public override async Task OnConnect()
        {
            var publisher = _publisherSessionService.FindPublisher(StreamName);
            if (publisher != null)
            {
                _cleanupActions.Add(() =>
                {
                    publisher.OnAudioMessage -= SendAudio;
                    publisher.OnVideoMessage -= SendVideo;
                });

                var metadata = (Dictionary<string, object>)publisher.FlvMetadata.Data.Last();
                var hasAudio = metadata.ContainsKey("audiocodecid");
                var hasVideo = metadata.ContainsKey("videocodecid");

                await Session.SendFlvHeaderAsync(hasAudio, hasVideo);

                await Session.SendMessageAsync(publisher.FlvMetadata);
                if (hasAudio)
                {
                    await Session.SendMessageAsync(publisher.AACConfigureRecord);
                }
                if (hasVideo)
                {
                    await Session.SendMessageAsync(publisher.AVCConfigureRecord);
                }

                publisher.OnAudioMessage += SendAudio;
                publisher.OnVideoMessage += SendVideo;
            }
            // play record
            else
            {
                _recordFile = new FileStream(_recordService.GetRecordFilename(StreamName) + ".flv", FileMode.Open, FileAccess.Read);
                var fromStr = Query.Get("from");
                long from = 0;
                if (fromStr != null)
                {
                    from = long.Parse(fromStr);
                }
                var toStr = Query.Get("to");
                _playRangeTo = -1;
                if (toStr != null)
                {
                    _playRangeTo = long.Parse(toStr);
                }

                var header = new byte[9];

                await _recordFile.ReadBytesAsync(header);
                await Session.SendRawDataAsync(header);

                from = Math.Max(from, 9);

                _recordFile.Seek(from, SeekOrigin.Begin);

                await PlayRecordFile();
            }
        }

19 View Source File : PackageManifestUpdater.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

internal static void EnsureMSBuildForUnity()
        {
            PackageManifest manifest = null;

            string manifestPath = GetPackageManifestFilePath();
            if (string.IsNullOrWhiteSpace(manifestPath))
            {
                return;
            }

            // Read the package manifest into a list of strings (for easy finding of entries)
            // and then deserialize.
            List<string> manifestFileLines = new List<string>();
            using (FileStream manifestStream = new FileStream(manifestPath, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader reader = new StreamReader(manifestStream))
                {
                    // Read the manifest file a line at a time.
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        manifestFileLines.Add(line);
                    }

                    // Go back to the start of the file.
                    manifestStream.Seek(0, 0);

                    // Deserialize the scoped registries portion of the package manifest.
                    manifest = JsonUtility.FromJson<PackageManifest>(reader.ReadToEnd());
                }
            }

            if (manifest == null)
            {
                Debug.LogError($"Failed to read the package manifest file ({manifestPath})");
                return;
            }

            // Ensure that pre-existing scoped registries are retained.
            List<ScopedRegistry> scopedRegistries = new List<ScopedRegistry>();
            if ((manifest.scopedRegistries != null) && (manifest.scopedRegistries.Length > 0))
            {
                scopedRegistries.AddRange(manifest.scopedRegistries);
            }

            // Attempt to find an entry in the scoped registries collection for the MSBuild for Unity URL
            bool needToAddRegistry = true;
            foreach (ScopedRegistry registry in scopedRegistries)
            {
                if (registry.url == MSBuildRegistryUrl)
                {
                    needToAddRegistry = false;
                }
            }

            // If no entry was found, add one.
            if (needToAddRegistry)
            {
                ScopedRegistry registry = new ScopedRegistry();
                registry.name = MSBuildRegistryName;
                registry.url = MSBuildRegistryUrl;
                registry.scopes = MSBuildRegistryScopes;

                scopedRegistries.Add(registry);
            }

            // Update the manifest's scoped registries, as the collection may have been modified.
            manifest.scopedRegistries = scopedRegistries.ToArray();

            int dependenciesStartIndex = -1;
            int scopedRegistriesStartIndex = -1;
            int scopedRegistriesEndIndex = -1;
            int packageLine = -1;

            // Presume that we need to add the MSBuild for Unity package. If this value is false,
            // we will check to see if the currently configured version meets or exceeds the
            // minimum requirements.
            bool needToAddPackage = true;

            // Attempt to find the MSBuild for Unity package entry in the dependencies collection
            // This loop also identifies the dependencies collection line and the start / end of a
            // pre-existing scoped registries collections
            for (int i = 0; i < manifestFileLines.Count; i++)
            {
                if (manifestFileLines[i].Contains("\"scopedRegistries\":"))
                {
                    scopedRegistriesStartIndex = i;
                }
                if (manifestFileLines[i].Contains("],") && (scopedRegistriesStartIndex != -1) && (scopedRegistriesEndIndex == -1))
                {
                    scopedRegistriesEndIndex = i;
                }
                if (manifestFileLines[i].Contains("\"dependencies\": {"))
                {
                    dependenciesStartIndex = i;
                }
                if (manifestFileLines[i].Contains(MSBuildPackageName))
                {
                    packageLine = i;
                    needToAddPackage = false;
                }
            }

            // If no package was found add it to the dependencies collection.
            if (needToAddPackage)
            {
                // Add the package to the collection (pad the entry with four spaces)
                manifestFileLines.Insert(dependenciesStartIndex + 1, $"    \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",");
            }
            else
            {
                // Replace the line that currently exists
                manifestFileLines[packageLine] = $"    \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",";
            }

            // Update the manifest file.
            // First, serialize the scoped registry collection.
            string serializedRegistriesJson = JsonUtility.ToJson(manifest, true);

            // Ensure that the file is truncated to ensure it is always valid after writing.
            using (FileStream outFile = new FileStream(manifestPath, FileMode.Truncate, FileAccess.Write))
            {
                using (StreamWriter writer = new StreamWriter(outFile))
                {
                    bool scopedRegistriesWritten = false;

                    // Write each line of the manifest back to the file.
                    for (int i = 0; i < manifestFileLines.Count; i++)
                    {
                        if ((i >= scopedRegistriesStartIndex) && (i <= scopedRegistriesEndIndex))
                        {
                            // Skip these lines, they will be replaced.
                            continue;
                        }

                        if (!scopedRegistriesWritten && (i > 0))
                        {
                            // Trim the leading '{' and '\n' from the serialized scoped registries
                            serializedRegistriesJson = serializedRegistriesJson.Remove(0, 2);
                            // Trim, the trailing '\n' and '}'
                            serializedRegistriesJson = serializedRegistriesJson.Remove(serializedRegistriesJson.Length - 2);
                            // Append a trailing ',' to close the scopedRegistries node
                            serializedRegistriesJson = serializedRegistriesJson.Insert(serializedRegistriesJson.Length, ",");
                            writer.WriteLine(serializedRegistriesJson);

                            scopedRegistriesWritten = true;
                        }

                        writer.WriteLine(manifestFileLines[i]);
                    }
                }
            }
        }

19 View Source File : DatReader.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static byte[] ReadDat(FileStream stream, uint offset, uint size, uint blockSize)
        {
            var buffer = new byte[size];

            stream.Seek(offset, SeekOrigin.Begin);

            // Dat "file" is broken up into sectors that are not neccessarily congruous. Next address is stored in first four bytes of each sector.
            uint nextAddress = GetNextAddress(stream, 0);

            int bufferOffset = 0;

            while (size > 0)
            {
                if (size < blockSize)
                {
                    stream.Read(buffer, bufferOffset, Convert.ToInt32(size));
                    size = 0; // We know we've read the only/last sector, so just set this to zero to proceed.
                }
                else
                {
                    stream.Read(buffer, bufferOffset, Convert.ToInt32(blockSize) - 4); // Read in our sector into the buffer[]
                    bufferOffset += Convert.ToInt32(blockSize) - 4; // Adjust this so we know where in our buffer[] the next sector gets appended to
                    stream.Seek(nextAddress, SeekOrigin.Begin); // Move the file pointer to the start of the next sector we read above.
                    nextAddress = GetNextAddress(stream, 0); // Get the start location of the next sector.
                    size -= (blockSize - 4); // Decrease this by the amount of data we just read into buffer[] so we know how much more to go
                }
            }

            return buffer;
        }

19 View Source File : DatReader.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static uint GetNextAddress(FileStream stream, int relOffset)
        {
            // The location of the start of the next sector is the first four bytes of the current sector. This should be 0x00000000 if no next sector.
            byte[] nextAddressBytes = new byte[4];

            if (relOffset != 0)
                stream.Seek(relOffset, SeekOrigin.Current); // To be used to back up 4 bytes from the origin at the start

            stream.Read(nextAddressBytes, 0, 4);

            return BitConverter.ToUInt32(nextAddressBytes, 0);
        }

19 View Source File : EanAnimation.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public void Load(BinaryReader br, FileStream fs)
    {
        this.Offset = br.ReadInt32();
        this.Offset += 16;
        this.FrameCount = br.ReadInt32();
        this.MipWidth = br.ReadInt32();
        this.MipHeight = br.ReadInt32();
        this.StartX = br.ReadInt32();
        this.StartY = br.ReadInt32();
        this.TileCount = br.ReadUInt16();
        this.TotalCount = br.ReadUInt16();
        this.CellWidth = br.ReadUInt16();
        this.CellHeight = br.ReadUInt16();
        this.Frames = new EanFrame[(int)this.TotalCount];
        long position = fs.Position;
        fs.Seek((long)this.Offset, SeekOrigin.Begin);
        for (int i = 0; i < (int)this.TotalCount; i++)
        {
            this.Frames[i].X = br.ReadUInt16();
            this.Frames[i].Y = br.ReadUInt16();
            this.Frames[i].Width = br.ReadUInt16();
            this.Frames[i].Height = br.ReadUInt16();
        }
        fs.Seek(position, SeekOrigin.Begin);
    }

19 View Source File : SaveInPlaceOperation.cs
License : GNU General Public License v2.0
Project Creator : afrantzis

protected override void DoOperation()
	{
		stageReached = SaveInPlaceStage.BeforeClose;

		// Open the file for editing.
		// Do this in the beginning to figure out if we have all the
		// required permissions before invalidating the byteBuffer.
		fs = new FileStream(savePath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
		
		// hold a reference to the bytebuffer's segment collection
		// because it is lost when the file is closed
		SegmentCollection segCol = byteBuffer.segCol;
		
		// close file
		if (!cancelled) {
			// close the file, make sure that File Operations
			// are temporarily allowed
			lock(byteBuffer.LockObj) {
				// CloseFile invalidates the file buffer,
				// so make sure undo/redo data stays valid
				byteBuffer.MakePrivateCopyOfUndoRedo();
				byteBuffer.FileOperationsAllowed = true;
				byteBuffer.CloseFile();
				byteBuffer.FileOperationsAllowed = false;
			}
		}
		
		stageReached = SaveInPlaceStage.BeforeWrite;
		
		const int blockSize = 0xffff;
		
		byte[] baTemp = new byte[blockSize];
		
		//
		// Just save the changed parts...
		//
		
		Util.List<Segment>.Node node = segCol.List.First;
		
		// hold the mapping of the start of the current segment
		// (at which offset in the file it is mapped)
		long mapping = 0;
		
		while (node != null && !cancelled)
		{
			// Save the data in the node 
			// in blocks of blockSize each
			Segment s = node.data;
			
			// if the segment belongs to the original buffer, skip it
			if (s.Buffer.GetType() == typeof(FileBuffer)) {
				mapping += s.Size;
				node = node.next;
				continue;
			}
				
			long len = s.Size;
			long nBlocks = len/blockSize;
			int last = (int)(len % blockSize); // bytes in last block
			long i;
			
			// move the file cursor to the current mapping
			fs.Seek(mapping, SeekOrigin.Begin);
			
			bytesSaved = mapping;
			
			// for every full block
			for (i = 0; i < nBlocks; i++) {
				s.Buffer.Read(baTemp, 0, s.Start + i * blockSize, blockSize);	
				fs.Write(baTemp, 0, blockSize);
				bytesSaved = (i + 1) * blockSize;
				
				if (cancelled)
					break;	
			}
		
			// if last non-full block is not empty
			if (last != 0 && !cancelled) {
				s.Buffer.Read(baTemp, 0, s.Start + i * blockSize, last);
				fs.Write(baTemp, 0, last);
			}
			
			mapping += s.Size;
			node = node.next;
		}	
		
		fs.Close();
		fs = null;	
	}

19 View Source File : KeyUtil.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public byte[] FindKey(string gamePath)
        {
            var gameExe = Path.Combine(gamePath, ExecutableName);

            const string validHash = "DEA375EF1E6EF2223A1221C2C575C47BF17EFA5E";
            byte[] key = null;

            var fs = new FileStream(gameExe, FileMode.Open, FileAccess.Read);

            foreach (var u in SearchOffsets)
            {
                if (u <= fs.Length - 32)
                {
                    var tempKey = new byte[32];
                    fs.Seek(u, SeekOrigin.Begin);
                    fs.Read(tempKey, 0, 32);

                    var hash = BitConverter.ToString(SHA1.Create().ComputeHash(tempKey)).Replace("-", "");
                    if (hash == validHash)
                    {
                        key = tempKey;
                        break;
                    }
                }
            }

            fs.Close();

            return key;
        }

19 View Source File : File.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public void Rebuild()
        {
            if (Header.EntryCount > 0)
            {
                string tempFilename = _filename + ".temp";
                var tempFS = new FileStream(tempFilename, FileMode.Create, FileAccess.Write);
                try
                {
                    var bw = new BinaryWriter(tempFS);

                    Header.Write(bw);

                    // Recalculate the offset/sizes of the TOC entries
                    var tocOffset = tempFS.Position;

                    var dataOffset = TOC.GetTOCBlockSize();

                    tempFS.Seek(dataOffset * TOCEntry.BlockSize, SeekOrigin.Begin);
                    foreach (var entry in TOC)
                    {
                        if (entry.CustomData == null)
                        {
                            bw.Write(ReadData(entry.OffsetBlock * TOCEntry.BlockSize, entry.UsedBlocks * TOCEntry.BlockSize));
                        }
                        else
                        {
                            var blockCount = (int) Math.Ceiling((float) entry.CustomData.Length/TOCEntry.BlockSize);
                            entry.UsedBlocks = (short)blockCount;
                            
                            bw.Write( entry.CustomData );
                            
                            if ( (entry.CustomData.Length % TOCEntry.BlockSize) != 0 )
                            {
                                var padding = new byte[ blockCount * TOCEntry.BlockSize - entry.CustomData.Length ];
                                bw.Write(padding);
                            }
                        }
                        entry.OffsetBlock = dataOffset;
                        dataOffset += entry.UsedBlocks;
                    }

                    tempFS.Seek(tocOffset, SeekOrigin.Begin);

                    TOC.Write( bw );

                }
                finally
                {
                    tempFS.Close();
                }

                Close();
                
                System.IO.File.Delete( _filename );
                System.IO.File.Move( tempFilename, _filename );

                Open(_filename);
            }
        }

19 View Source File : File.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public void Rebuild()
        {
            if (Header.EntryCount > 0)
            {
                string tempFilename = _filename + ".temp";
                var tempFS = new FileStream(tempFilename, FileMode.Create, FileAccess.Write);
                try
                {
                    var bw = new BinaryWriter(tempFS);

                    Header.Write(bw);

                    // Recalculate the offset/sizes of the TOC entries
                    var tocOffset = tempFS.Position;

                    var dataOffset = TOC.GetTOCBlockSize();

                    tempFS.Seek(dataOffset * TOCEntry.BlockSize, SeekOrigin.Begin);
                    foreach (var entry in TOC)
                    {
                        if (entry.CustomData == null)
                        {
                            bw.Write(ReadData(entry.OffsetBlock * TOCEntry.BlockSize, entry.UsedBlocks * TOCEntry.BlockSize));
                        }
                        else
                        {
                            var blockCount = (int) Math.Ceiling((float) entry.CustomData.Length/TOCEntry.BlockSize);
                            entry.UsedBlocks = (short)blockCount;
                            
                            bw.Write( entry.CustomData );
                            
                            if ( (entry.CustomData.Length % TOCEntry.BlockSize) != 0 )
                            {
                                var padding = new byte[ blockCount * TOCEntry.BlockSize - entry.CustomData.Length ];
                                bw.Write(padding);
                            }
                        }
                        entry.OffsetBlock = dataOffset;
                        dataOffset += entry.UsedBlocks;
                    }

                    tempFS.Seek(tocOffset, SeekOrigin.Begin);

                    TOC.Write( bw );

                }
                finally
                {
                    tempFS.Close();
                }

                Close();
                
                System.IO.File.Delete( _filename );
                System.IO.File.Move( tempFilename, _filename );

                Open(_filename);
            }
        }

19 View Source File : PackageDownloadsJsonSource.cs
License : MIT License
Project Creator : ai-traders

private async Task<Stream> GetDownloadsStreamAsync()
        {
            _logger.LogInformation("Downloading downloads.v1.json...");

            var fileStream = File.Open(Path.GetTempFileName(), FileMode.Create);
            var response = await _httpClient.GetAsync(PackageDownloadsV1Url, HttpCompletionOption.ResponseHeadersRead);

            response.EnsureSuccessStatusCode();

            using (var networkStream = await response.Content.ReadreplacedtreamAsync())
            {
                await networkStream.CopyToAsync(fileStream);
            }

            fileStream.Seek(0, SeekOrigin.Begin);

            _logger.LogInformation("Downloaded downloads.v1.json");

            return fileStream;
        }

19 View Source File : GGPKContainer.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

public virtual BaseRecord GetRecord(long? offset = null) {
            if (offset.HasValue)
                FileStream.Seek(offset.Value, SeekOrigin.Begin);
            var length = Reader.ReadInt32();
            var tag = Reader.ReadBytes(4);
            if (tag.SequenceEqual(FileRecord.Tag))
                return new FileRecord(length, this);
            else if (tag.SequenceEqual(DirectoryRecord.Tag))
                return new DirectoryRecord(length, this);
            else if (tag.SequenceEqual(FreeRecord.Tag))
                return new FreeRecord(length, this);
            else if (tag.SequenceEqual(GGPKRecord.Tag))
                return new GGPKRecord(length, this);
            else
                throw new Exception("Invalid Record Tag: " + Encoding.UTF8.GetString(tag) + " at offset: " + (FileStream.Position - 8).ToString());
        }

19 View Source File : GGPKContainer.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

public virtual BaseRecord GetRecord(long? offset = null)
        {
            if (offset.HasValue)
                fileStream.Seek(offset.Value, SeekOrigin.Begin);
            var length = Reader.ReadInt32();
            var tag = Reader.ReadBytes(4);
            if (tag.SequenceEqual(FileRecord.Tag))
                return new FileRecord(length, this);
            else if (tag.SequenceEqual(FreeRecord.Tag))
                return new FreeRecord(length, this);
            else if (tag.SequenceEqual(DirectoryRecord.Tag))
                return new DirectoryRecord(length, this);
            else if (tag.SequenceEqual(GGPKRecord.Tag))
                return new GGPKRecord(length, this);
            else
                throw new Exception("Invalid Record Tag: " + Encoding.ASCII.GetString(tag) + " at offset: " + (fileStream.Position - 8).ToString());
        }

19 View Source File : CommonMethods.cs
License : MIT License
Project Creator : alecgn

public static byte[] GetBytesFromFile(string filePath, int dataLength, long offset = 0)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException($"{MessageStrings.Common_FileNotFound} {filePath}.", filePath);
            }

            if (dataLength < 1)
            {
                throw new ArgumentException($"{MessageStrings.Common_InvalidDataLengthError} ({dataLength}).", nameof(dataLength));
            }

            var dataBytes = new byte[dataLength];

            using (var fStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                fStream.Seek(offset, SeekOrigin.Begin);
                fStream.Read(dataBytes, 0, dataLength);
                fStream.Close();
            }

            return dataBytes;
        }

19 View Source File : NPPIMage.cs
License : MIT License
Project Creator : altimesh

public static NPPImage Load(string path, cudaStream_t stream)
        {
            NPPImage result = new NPPImage();
            byte[] rawData;
            if (Path.GetExtension(path).Contains("pgm"))
            {
                using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                    using (TextReader tReader = new StreamReader(fs))
                    using (BinaryReader bReader = new BinaryReader(fs))
                    {
                        string formatLine = tReader.ReadLine(); // skip
                        string sizeLine = tReader.ReadLine();
                        string[] splitted = sizeLine.Split(' ');
                        result.width = int.Parse(splitted[0]);
                        result.height = int.Parse(splitted[1]);

                        string maxValueLine = tReader.ReadLine(); // skip
                        int pos = formatLine.Length + sizeLine.Length + maxValueLine.Length + 3;
                        fs.Seek(pos, SeekOrigin.Begin);

                        // TODO: optimize that part
                        rawData = bReader.ReadBytes((int)(fs.Length - pos));

                    }
                }
            }
            else if (Path.GetExtension(path).Contains("png"))
            {
                Bitmap image = Bitmap.FromFile(path) as Bitmap;
                result.width = image.Width;
                result.height = image.Height;
                rawData = new byte[result.width * result.height];
                int index = 0;
                for (int j = 0; j < result.height; ++j)
                {
                    for (int i = 0; i < result.width; ++i, ++index)
                    {
                        rawData[index] = image.GetPixel(i, j).R;
                    }
                }
            }
            else
            {
                throw new NotSupportedException("unsupported file format");
            }

            IntPtr deviceData;
            size_t p;
            cuda.ERROR_CHECK(cuda.MallocPitch(out deviceData, out p, result.width * sizeof(ushort), result.height));
            result.pitch = (int)p;

            result.hostData = new ushort[result.height * result.width];
            for (int j = 0; j < result.height; ++j)
            {
                for (int i = 0; i < result.width; ++i)
                {
                    result.hostData[j * result.width + i] = rawData[j * result.width + i];
                }
            }

            var handle = GCHandle.Alloc(result.hostData, GCHandleType.Pinned);
            cuda.ERROR_CHECK(cuda.Memcpy2DAsync(deviceData, p, handle.AddrOfPinnedObject(), result.width * sizeof(ushort), result.width * sizeof(ushort), result.height, cudaMemcpyKind.cudaMemcpyHostToDevice, stream));
            handle.Free();
            result.deviceData = deviceData;

            return result;
        }

19 View Source File : SelfUpdateProgressPage.cs
License : GNU General Public License v3.0
Project Creator : Amebis

public override void OnActivate()
        {
            base.OnActivate();

            // Setup self-update.
            var selfUpdate = new BackgroundWorker() { WorkerReportsProgress = true };
            selfUpdate.DoWork += (object sender, DoWorkEventArgs e) =>
            {
                selfUpdate.ReportProgress(0);
                var random = new Random();
                var tempFolder = Path.GetTempPath();
                var workingFolder = tempFolder + Path.GetRandomFileName() + "\\";
                Directory.CreateDirectory(workingFolder);
                try
                {
                    string installerFilename = null;
                    FileStream installerFile = null;

                    // Download installer.
                    while (DownloadUris.Count > 0)
                    {
                        Window.Abort.Token.ThrowIfCancellationRequested();
                        var uriIndex = random.Next(DownloadUris.Count);
                        try
                        {
                            var binaryUri = DownloadUris[uriIndex];
                            Trace.TraceInformation("Downloading installer file from {0}...", binaryUri.AbsoluteUri);
                            var request = WebRequest.Create(binaryUri);
                            request.Proxy = null;
                            using (var response = request.GetResponse())
                            {
                                // 1. Get installer filename from Content-Disposition header.
                                // 2. Get installer filename from the last segment of URI path.
                                // 3. Fallback to a predefined installer filename.
                                try { installerFilename = Path.GetFullPath(workingFolder + new ContentDisposition(request.Headers["Content-Disposition"]).FileName); }
                                catch
                                {
                                    try { installerFilename = Path.GetFullPath(workingFolder + binaryUri.Segments[binaryUri.Segments.Length - 1]); }
                                    catch { installerFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup.exe"); }
                                }

                                // Save response data to file.
                                installerFile = File.Open(installerFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
                                try
                                {
                                    using (var stream = response.GetResponseStream())
                                    {
                                        installerFile.Seek(0, SeekOrigin.Begin);
                                        var hash = new eduEd25519.SHA256();
                                        var buffer = new byte[1048576];
                                        long offset = 0, total = response.ContentLength;

                                        for (; ; )
                                        {
                                            // Wait for the data to arrive.
                                            Window.Abort.Token.ThrowIfCancellationRequested();
                                            var bufferLength = stream.Read(buffer, 0, buffer.Length);
                                            if (bufferLength == 0)
                                                break;
                                            //Window.Abort.Token.WaitHandle.WaitOne(100); // Mock a slow link for testing.

                                            // Append it to the file and hash it.
                                            Window.Abort.Token.ThrowIfCancellationRequested();
                                            installerFile.Write(buffer, 0, bufferLength);
                                            hash.TransformBlock(buffer, 0, bufferLength, buffer, 0);

                                            // Report progress.
                                            offset += bufferLength;
                                            selfUpdate.ReportProgress((int)(offset * 100 / total));
                                        }

                                        hash.TransformFinalBlock(buffer, 0, 0);
                                        if (!hash.Hash.SequenceEqual(Hash))
                                            throw new DownloadedFileCorruptException(string.Format(Resources.Strings.ErrorDownloadedFileCorrupt, binaryUri.AbsoluteUri));

                                        installerFile.SetLength(installerFile.Position);
                                        break;
                                    }
                                }
                                catch
                                {
                                    // Close installer file.
                                    installerFile.Close();
                                    installerFile = null;

                                    // Delete installer file. If possible.
                                    Trace.TraceInformation("Deleting file {0}...", installerFilename);
                                    try { File.Delete(installerFilename); }
                                    catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }
                                    installerFilename = null;

                                    throw;
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception ex)
                        {
                            Trace.TraceWarning("Error: {0}", ex.ToString());
                            DownloadUris.RemoveAt(uriIndex);
                        }
                    }

                    if (installerFilename == null || installerFile == null)
                    {
                        // The installer file is not ready.
                        throw new InstallerFileUnavailableException();
                    }

                    try
                    {
                        var updaterFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup and Relaunch.wsf");
                        var updaterFile = File.Open(updaterFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
                        try
                        {
                            // Prepare WSF file.
                            var writer = new XmlTextWriter(updaterFile, null);
                            writer.WriteStartDoreplacedent();
                            writer.WriteStartElement("package");
                            writer.WriteStartElement("job");

                            writer.WriteStartElement("reference");
                            writer.WriteAttributeString("object", "WScript.Shell");
                            writer.WriteEndElement(); // reference

                            writer.WriteStartElement("reference");
                            writer.WriteAttributeString("object", "Scripting.FileSystemObject");
                            writer.WriteEndElement(); // reference

                            writer.WriteStartElement("script");
                            writer.WriteAttributeString("language", "JScript");
                            var installerArgumentsEsc = string.IsNullOrEmpty(Arguments) ? "" : " " + HttpUtility.JavaScriptStringEncode(Arguments);
                            var argv = Environment.GetCommandLineArgs();
                            var arguments = new StringBuilder();
                            for (long i = 1, n = argv.LongLength; i < n; i++)
                            {
                                if (i > 1) arguments.Append(" ");
                                arguments.Append("\"");
                                arguments.Append(argv[i].Replace("\"", "\"\""));
                                arguments.Append("\"");
                            }
                            var script = new StringBuilder();
                            script.AppendLine("var wsh = WScript.CreateObject(\"WScript.Shell\");");
                            script.AppendLine("wsh.Run(\"\\\"" + HttpUtility.JavaScriptStringEncode(installerFilename.Replace("\"", "\"\"")) + "\\\"" + installerArgumentsEsc + "\", 0, true);");
                            script.AppendLine("var fso = WScript.CreateObject(\"Scripting.FileSystemObject\");");
                            script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(installerFilename) + "\", true); } catch (err) {}");
                            script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(updaterFilename) + "\", true); } catch (err) {}");
                            script.AppendLine("try { fso.DeleteFolder(\"" + HttpUtility.JavaScriptStringEncode(workingFolder.TrimEnd(Path.DirectorySeparatorChar)) + "\", true); } catch (err) {}");
                            writer.WriteCData(script.ToString());
                            writer.WriteEndElement(); // script

                            writer.WriteEndElement(); // job
                            writer.WriteEndElement(); // package
                            writer.WriteEndDoreplacedent();
                            writer.Flush();

                            // Prepare WSF launch parameters.
                            Trace.TraceInformation("Launching update script file {0}...", updaterFilename);
                            var process = new Process();
                            process.StartInfo.FileName = "wscript.exe";
                            process.StartInfo.Arguments = "\"" + updaterFilename + "\"";
                            process.StartInfo.WorkingDirectory = workingFolder;

                            // Close WSF and installer files as late as possible to narrow the attack window.
                            // If Windows supported executing files that are locked for writing, we could leave those files open.
                            updaterFile.Close();
                            installerFile.Close();
                            process.Start();
                        }
                        catch
                        {
                            // Close WSF file.
                            updaterFile.Close();

                            // Delete WSF file. If possible.
                            Trace.TraceInformation("Deleting file {0}...", updaterFilename);
                            try { File.Delete(updaterFilename); }
                            catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", updaterFilename, ex2.ToString()); }

                            throw;
                        }
                    }
                    catch
                    {
                        // Close installer file.
                        installerFile.Close();

                        // Delete installer file. If possible.
                        Trace.TraceInformation("Deleting file {0}...", installerFilename);
                        try { File.Delete(installerFilename); }
                        catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }

                        throw;
                    }
                }
                catch
                {
                    // Delete working folder. If possible.
                    try { Directory.Delete(workingFolder); }
                    catch (Exception ex2) { Trace.TraceWarning("Deleting {0} folder failed: {1}", workingFolder, ex2.ToString()); }

                    throw;
                }
            };

            // Self-update progress.
            selfUpdate.ProgressChanged += (object sender, ProgressChangedEventArgs e) =>
            {
                Progress.Value = e.ProgressPercentage;
            };

            // Self-update complereplacedion.
            selfUpdate.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) =>
            {
                if (e.Error == null)
                {
                    // Self-updating successfuly launched. Quit to release open files.
                    Wizard.OnQuitApplication(this);
                }
                else
                    Wizard.Error = e.Error;

                // Self-dispose.
                (sender as BackgroundWorker)?.Dispose();
            };

            selfUpdate.RunWorkerAsync();
        }

19 View Source File : Functions.cs
License : Apache License 2.0
Project Creator : AmpScm

public static bool IsBinaryFile(FileStream F)
        {
            F.Seek(0, SeekOrigin.Begin);

            //First see if the file begins with any known Unicode byte order marks.
            //If so, then it is a text file.  Use a StreamReader instance to do the
            //auto-detection logic.
            //
            //NOTE: I'm not disposing of the StreamReader because that closes the
            //replacedociated Stream.  The caller opened the file stream, so they should
            //be the one to close it.
            StreamReader Reader = new StreamReader(F, Encoding.Default, true);
            Reader.Read(); //We have to force a Read for it to auto-detect.
            if (Reader.CurrentEncoding != Encoding.Default)
            {
                return false;
            }
            Reader.DiscardBufferedData();
            Reader = null;

            //Since the type was Default encoding, that means there were no byte-order
            //marks to indicate its type.  So we have to scan.  If we find a NULL
            //character in the stream, that means it's a binary file.
            F.Seek(0, SeekOrigin.Begin);
            int i;
            while ((i = F.ReadByte()) > -1)
            {
                if (i == 0)
                {
                    return true;
                }
            }

            return false;
        }

19 View Source File : WAD.cs
License : GNU General Public License v3.0
Project Creator : anotak

private void ReadHeaders()
		{
			int offset, length;
			byte[] fixedname;
			
			// Make sure the write is finished writing
			if(!isreadonly) writer.Flush();

			// Seek to beginning
			file.Seek(0, SeekOrigin.Begin);

			// Read WAD type
			type = ENCODING.GetString(reader.ReadBytes(4));
			
			// Number of lumps
			numlumps = reader.ReadInt32();
			if(numlumps < 0) throw new IOException("Invalid number of lumps in wad file.");

			// Lumps table offset
			lumpsoffset = reader.ReadInt32();
			if(lumpsoffset < 0) throw new IOException("Invalid lumps offset in wad file.");

			// Seek to the lumps table
			file.Seek(lumpsoffset, SeekOrigin.Begin);
			
			// Dispose old lumps and create new list
			if(lumps != null) foreach(Lump l in lumps) l.Dispose();
			lumps = new List<Lump>(numlumps);

			// Go for all lumps
			for(int i = 0; i < numlumps; i++)
			{
				// Read lump information
				offset = reader.ReadInt32();
				length = reader.ReadInt32();
				fixedname = reader.ReadBytes(8);

				// Create the lump
				lumps.Add(new Lump(file, this, fixedname, offset, length));
			}
		}

19 View Source File : WAD.cs
License : GNU General Public License v3.0
Project Creator : anotak

public void WriteHeaders()
		{
			// Seek to beginning
			file.Seek(0, SeekOrigin.Begin);

			// Write WAD type
			writer.Write(ENCODING.GetBytes(type));

			// Number of lumps
			writer.Write(numlumps);

			// Lumps table offset
			writer.Write(lumpsoffset);

			// Seek to the lumps table
			file.Seek(lumpsoffset, SeekOrigin.Begin);

			// Go for all lumps
			for(int i = 0; i < lumps.Count; i++)
			{
				// Write lump information
				writer.Write(lumps[i].Offset);
				writer.Write(lumps[i].Length);
				writer.Write(lumps[i].FixedName);
			}
		}

19 View Source File : UnityWebRequestRenewalAsync.cs
License : MIT License
Project Creator : AnotherEnd15

public async ETTask DownloadAsync(string url, string filePath, int packageLength = 1000000, int maxCount = 20)
        {
            try
            {
                url                = url.Replace(" ", "%20");
                this.Url           = url;
                this.packageLength = packageLength;
                this.maxCount      = maxCount;
                Log.Debug("Web Request:" + url);

                #region Download File Header

                this.requestType = RequestType.Head;
                //下载文件头
                Log.Debug($"Request Head: {Url}");
                this.tcs         = new ETTaskCompletionSource();
                this.headRequest = UnityWebRequest.Head(Url);
                this.headRequest.SendWebRequest();
                await this.tcs.Task;
                this.totalBytes = long.Parse(this.headRequest.GetResponseHeader("Content-Length"));
                string modifiedTime = this.headRequest.GetResponseHeader("Last-Modified");
                Log.Debug($"totalBytes: {this.totalBytes}");
                this.headRequest?.Dispose();
                this.headRequest = null;

                #endregion

                #region Check Local File
                //打开或创建
                fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
                //获取已下载长度
                this.byteWrites = fileStream.Length;
                //通过本地缓存的服务器文件修改时间和文件总长度检测服务器是否是同一个文件 不是同一个从头开始写入
                if (!CheckSameFile(modifiedTime))
                    this.byteWrites = 0;
                Log.Debug($"byteWrites: {this.byteWrites}");
                if (this.byteWrites == this.totalBytes)
                {
                    Log.Debug("已经下载完成2");
                    return;
                }

                //设置开始写入位置
                fileStream.Seek(this.byteWrites, SeekOrigin.Begin);

                #endregion

                #region Download File Data

                //下载文件数据
                requestType = RequestType.Data;
                Log.Debug($"Request Data: {Url}");
                this.tcs = new ETTaskCompletionSource();
                this.DownloadPackages();
                await this.tcs.Task;

                #endregion
            }
            catch (Exception e)
            {
                Log.Error($"下载:{Url} Exception:{e}");
                throw;
            }
        }

19 View Source File : SaveEndpoints.cs
License : GNU General Public License v3.0
Project Creator : AnyStatus

public async Task<bool> Handle(Request request, CancellationToken cancellationToken)
            {
                var directory = Path.GetDirectoryName(_appSettings.EndpointsFilePath);

                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                var json = JsonConvert.SerializeObject(_context.Endpoints, Formatting.Indented, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.All,
                    PreserveReferencesHandling = PreserveReferencesHandling.Objects
                });

                var bytes = new UTF8Encoding().GetBytes(json);

                using (var stream = File.Open(_appSettings.EndpointsFilePath, FileMode.Create))
                {
                    stream.Seek(0, SeekOrigin.End);

                    await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false);
                }

                return true;
            }

19 View Source File : SaveSession.cs
License : GNU General Public License v3.0
Project Creator : AnyStatus

public async Task<bool> Handle(Request request, CancellationToken cancellationToken)
            {
                var directory = Path.GetDirectoryName(_appSettings.SessionFilePath);

                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                var json = JsonConvert.SerializeObject(_context.Session, Formatting.Indented);

                var bytes = new UTF8Encoding().GetBytes(json);

                using (var stream = File.Open(_appSettings.SessionFilePath, FileMode.Create))
                {
                    stream.Seek(0, SeekOrigin.End);

                    await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false);
                }

                return true;
            }

19 View Source File : SaveUserSettings.cs
License : GNU General Public License v3.0
Project Creator : AnyStatus

public async Task<bool> Handle(Request request, CancellationToken cancellationToken)
            {
                var directory = Path.GetDirectoryName(_appSettings.UserSettingsFilePath);

                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                var json = JsonConvert.SerializeObject(_context.UserSettings, Formatting.Indented);

                var bytes = new UTF8Encoding().GetBytes(json);

                using (var stream = File.Open(_appSettings.UserSettingsFilePath, FileMode.Create))
                {
                    stream.Seek(0, SeekOrigin.End);

                    await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false);
                }

                return true;
            }

19 View Source File : SaveWidget.cs
License : GNU General Public License v3.0
Project Creator : AnyStatus

public async Task<bool> Handle(Request request, CancellationToken cancellationToken)
            {
                var directory = Path.GetDirectoryName(request.FileName);

                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                var json = JsonConvert.SerializeObject(request.Widget, Formatting.Indented, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.All,
                    PreserveReferencesHandling = PreserveReferencesHandling.Objects
                });

                var bytes = new UTF8Encoding().GetBytes(json);

                using (var stream = File.Open(request.FileName, FileMode.Create))
                {
                    stream.Seek(0, SeekOrigin.End);

                    await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false);
                }

                return true;
            }

19 View Source File : Issues.cs
License : Apache License 2.0
Project Creator : Appdynamics

[Ignore]
        [TestMethod]
        public void Issue15159()
        {
            var fs = new FileStream(@"C:\temp\bug\DeleteColFormula\FormulasIssue\demo.xlsx", FileMode.OpenOrCreate);
            using (var package = new OfficeOpenXml.ExcelPackage(fs))
            {
                package.Save();
            }
            fs.Seek(0, SeekOrigin.Begin);
            var fs2 = fs;
        }

19 View Source File : Binary_filetype.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

public static IEnumerable<TreeNode> OpenFile(string fileName, List<(string, Dictionary<string, object>)> moduleSuggestions, Action<double> progressAction, Func<RSAParameters?, bool> askForCodePermission)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
			
			List<Attachment> attachments = new List<Attachment>();

            if (BinaryTree.HasValidTrailer(fs, true))
            {
                try
                {
                    using (BinaryReader reader = new BinaryReader(fs, System.Text.Encoding.UTF8, true))
                    {
                        fs.Seek(-12, SeekOrigin.End);
                        long labelAddress = reader.ReadInt64();
                        fs.Seek(labelAddress - 8, SeekOrigin.Begin);
                        long dataLength = reader.ReadInt64();
                        if (dataLength > 11)
                        {
                            fs.Seek(labelAddress - 8 - dataLength, SeekOrigin.Begin);
                            string header = reader.ReadString();
							string serializedModules = null; 
							
                            if (header == "#TreeViewer")
                            {
                                serializedModules = reader.ReadString();

                                if (reader.BaseStream.Position - (labelAddress - 8 - dataLength) < dataLength)
                                {
                                    try
                                    {
                                        header = reader.ReadString();
                                    }
                                    catch { }
                                }
                            }


                            if (header == "#Attachments")
                            {
                                int attachmentCount = reader.ReadInt32();

                                for (int i = 0; i < attachmentCount; i++)
                                {
                                    Attachment att = ReadAttachment(reader, fileName);
									attachments.Add(att);
                                    moduleSuggestions.Add(("@Attachment", new Dictionary<string, object>() { { "Attachment", att } }));
                                }
                            }
							
							if (serializedModules != null)
							{
								List<List<(string, Dictionary<string, object>)>> modules = ModuleUtils.DeserializeModules(serializedModules, attachments, askForCodePermission);

                                if (modules[0].Count > 0)
                                {
                                    moduleSuggestions[0] = modules[0][0];
                                }

                                if (modules[2].Count > 0)
                                {
                                    moduleSuggestions[1] = modules[2][0];
                                }

                                for (int i = 0; i < modules[1].Count; i++)
                                {
                                    moduleSuggestions.Add(modules[1][i]);
                                }

                                for (int i = 0; i < modules[3].Count; i++)
                                {
                                    moduleSuggestions.Add(modules[3][i]);
                                }
							}
                        }
                    }
                }
                catch { }

                fs.Seek(0, SeekOrigin.Begin);

                return new TreeCollection(fs);
            }
            else
            {
                return BinaryTree.ParseTrees(fs, progressAction: progressAction);
            }
        }

19 View Source File : Apply_Transformer_action.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

public static async Task PerformAction(int index, MainWindow window)
        {
            string tempFileName = Path.GetTempFileName();

            using (System.IO.FileStream fs = new System.IO.FileStream(tempFileName, System.IO.FileMode.Create))
            {
                string tempFile = System.IO.Path.GetTempFileName();
                using (System.IO.FileStream ms = new System.IO.FileStream(tempFile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                {
                    using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms, System.Text.Encoding.UTF8, true))
                    {
                        bw.Write((byte)0);
                        bw.Write((byte)0);
                        bw.Write((byte)0);
                        bw.Write("#TreeViewer");
                        bw.Write(window.SerializeAllModules(MainWindow.ModuleTarget.ExcludeTransform, true));

                        if (window.StateData.Attachments.Count > 0)
                        {
                            bw.Write("#Attachments");
                            bw.Write(window.StateData.Attachments.Count);

                            foreach (KeyValuePair<string, Attachment> kvp in window.StateData.Attachments)
                            {
                                bw.Write(kvp.Key);
                                bw.Write(2);
                                bw.Write(kvp.Value.StoreInMemory);
                                bw.Write(kvp.Value.CacheResults);
                                bw.Write(kvp.Value.StreamLength);
                                bw.Flush();

                                kvp.Value.WriteToStream(ms);
                            }
                        }

                        bw.Flush();
                        bw.Write(ms.Position - 3);
                    }

                    ms.Seek(0, System.IO.SeekOrigin.Begin);

                    BinaryTree.WriteAllTrees(new TreeNode[] { window.FirstTransformedTree }, fs, additionalDataToCopy: ms);
                }
                System.IO.File.Delete(tempFile);
            }

            Avalonia.Controls.Window targetWindow = await window.LoadFile(tempFileName, true);

            MessageBox box = new MessageBox("Question", "Would you like to close the window with the original file?", MessageBox.MessageBoxButtonTypes.YesNo, MessageBox.MessageBoxIconTypes.QuestionMark);

            await box.ShowDialog2(targetWindow);

            if (box.Result == MessageBox.Results.Yes)
            {
                window.Close();
            }
        }

19 View Source File : Apply_modules_to_other_tree.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

public static async Task PerformAction(int index, MainWindow window)
        {
            OpenFileDialog dialog;

            List<FileDialogFilter> filters = new List<FileDialogFilter>();

            List<string> allExtensions = new List<string>();

            for (int i = 0; i < Modules.FileTypeModules.Count; i++)
            {
                filters.Add(new FileDialogFilter() { Name = Modules.FileTypeModules[i].Extensions[0], Extensions = new List<string>(Modules.FileTypeModules[i].Extensions.Skip(1)) });
                allExtensions.AddRange(Modules.FileTypeModules[i].Extensions.Skip(1));
            }

            filters.Insert(0, new FileDialogFilter() { Name = "All tree files", Extensions = allExtensions });
            filters.Add(new FileDialogFilter() { Name = "All files", Extensions = new List<string>() { "*" } });

            if (!Modules.IsMac)
            {
                dialog = new OpenFileDialog()
                {
                    replacedle = "Open tree file",
                    AllowMultiple = false,
                    Filters = filters
                };
            }
            else
            {
                dialog = new OpenFileDialog()
                {
                    replacedle = "Open tree file",
                    AllowMultiple = false
                };
            }

            string[] result = await dialog.ShowAsync(window);

            if (result != null && result.Length == 1)
            {
                TreeCollection coll = await LoadFile(result[0], window);

                if (coll != null)
                {
                    string tempFileName = Path.GetTempFileName();

                    using (System.IO.FileStream fs = new System.IO.FileStream(tempFileName, System.IO.FileMode.Create))
                    {
                        string tempFile = System.IO.Path.GetTempFileName();
                        using (System.IO.FileStream ms = new System.IO.FileStream(tempFile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                        {
                            using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms, System.Text.Encoding.UTF8, true))
                            {
                                bw.Write((byte)0);
                                bw.Write((byte)0);
                                bw.Write((byte)0);
                                bw.Write("#TreeViewer");
                                bw.Write(window.SerializeAllModules(MainWindow.ModuleTarget.AllModules, true));

                                if (window.StateData.Attachments.Count > 0)
                                {
                                    bw.Write("#Attachments");
                                    bw.Write(window.StateData.Attachments.Count);

                                    foreach (KeyValuePair<string, Attachment> kvp in window.StateData.Attachments)
                                    {
                                        bw.Write(kvp.Key);
                                        bw.Write(2);
                                        bw.Write(kvp.Value.StoreInMemory);
                                        bw.Write(kvp.Value.CacheResults);
                                        bw.Write(kvp.Value.StreamLength);
                                        bw.Flush();

                                        kvp.Value.WriteToStream(ms);
                                    }
                                }

                                bw.Flush();
                                bw.Write(ms.Position - 3);
                            }

                            ms.Seek(0, System.IO.SeekOrigin.Begin);

                            BinaryTree.WriteAllTrees(coll, fs, additionalDataToCopy: ms);
                        }

                        System.IO.File.Delete(tempFile);
                    }

                    await window.LoadFile(tempFileName, true);
                }
            }
        }

19 View Source File : Apply_Further_transformations.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

public static async Task PerformAction(int index, MainWindow window)
        {
            string tempFileName = Path.GetTempFileName();

            using (System.IO.FileStream fs = new System.IO.FileStream(tempFileName, System.IO.FileMode.Create))
            {
                string tempFile = System.IO.Path.GetTempFileName();
                using (System.IO.FileStream ms = new System.IO.FileStream(tempFile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                {
                    using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms, System.Text.Encoding.UTF8, true))
                    {
                        bw.Write((byte)0);
                        bw.Write((byte)0);
                        bw.Write((byte)0);
                        bw.Write("#TreeViewer");
                        bw.Write(window.SerializeAllModules(MainWindow.ModuleTarget.ExcludeFurtherTransformation, true));

                        if (window.StateData.Attachments.Count > 0)
                        {
                            bw.Write("#Attachments");
                            bw.Write(window.StateData.Attachments.Count);

                            foreach (KeyValuePair<string, Attachment> kvp in window.StateData.Attachments)
                            {
                                bw.Write(kvp.Key);
                                bw.Write(2);
                                bw.Write(kvp.Value.StoreInMemory);
                                bw.Write(kvp.Value.CacheResults);
                                bw.Write(kvp.Value.StreamLength);
                                bw.Flush();

                                kvp.Value.WriteToStream(ms);
                            }
                        }

                        bw.Flush();
                        bw.Write(ms.Position - 3);
                    }

                    ms.Seek(0, System.IO.SeekOrigin.Begin);

                    BinaryTree.WriteAllTrees(new TreeNode[] { window.TransformedTree }, fs, additionalDataToCopy: ms);
                }

                System.IO.File.Delete(tempFile);
            }

            Avalonia.Controls.Window targetWindow = await window.LoadFile(tempFileName, true);

            MessageBox box = new MessageBox("Question", "Would you like to close the window with the original file?", MessageBox.MessageBoxButtonTypes.YesNo, MessageBox.MessageBoxIconTypes.QuestionMark);

            await box.ShowDialog2(targetWindow);

            if (box.Result == MessageBox.Results.Yes)
            {
                window.Close();
            }
        }

public static void PerformAction(int actionIndex, MainWindow window, InstanceStateData stateData)
        {
            ConsoleWrapper.WriteLine();
            ConsoleWrapper.Write("Enter path to the other tree file: ");
            string fileName = ConsoleWrapper.ReadLine();

            if (!string.IsNullOrEmpty(fileName))
            {
                if (File.Exists(fileName))
                {
                    
                    TreeCollection coll = LoadFile(fileName);

                    if (coll != null)
                    {
                        string tempFileName = Path.GetTempFileName();

                        using (System.IO.FileStream fs = new System.IO.FileStream(tempFileName, System.IO.FileMode.Create))
                        {
                            string tempFile = System.IO.Path.GetTempFileName();
                            using (System.IO.FileStream ms = new System.IO.FileStream(tempFile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                            {
                                using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms, System.Text.Encoding.UTF8, true))
                                {
                                    bw.Write((byte)0);
                                    bw.Write((byte)0);
                                    bw.Write((byte)0);
                                    bw.Write("#TreeViewer");
                                    
                                    bw.Write(stateData.SerializeAllModules(MainWindow.ModuleTarget.AllModules, true));

                                    if (stateData.Attachments.Count > 0)
                                    {
                                        bw.Write("#Attachments");
                                        bw.Write(stateData.Attachments.Count);

                                        foreach (KeyValuePair<string, Attachment> kvp in stateData.Attachments)
                                        {
                                            bw.Write(kvp.Key);
                                            bw.Write(2);
                                            bw.Write(kvp.Value.StoreInMemory);
                                            bw.Write(kvp.Value.CacheResults);
                                            bw.Write(kvp.Value.StreamLength);
                                            bw.Flush();

                                            kvp.Value.WriteToStream(ms);
                                        }
                                    }

                                    bw.Flush();
                                    bw.Write(ms.Position - 3);
                                }

                                ms.Seek(0, System.IO.SeekOrigin.Begin);

                                BinaryTree.WriteAllTrees(coll, fs, additionalDataToCopy: ms);
                            }

                            System.IO.File.Delete(tempFile);
                        }

                        stateData.OpenFile(tempFileName, true);
                    }
                }
                else
                {
                    ConsoleWrapper.WriteLine();
                    ConsoleWrapper.WriteLine(new ConsoleTextSpan("The selected file does not exist!", ConsoleColor.Red));
                    ConsoleWrapper.WriteLine();
                }
            }
        }

19 View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

private static List<string> ExportCurrentlyOpenTrees()
        {
            List<string> treeFiles = new List<string>();

            foreach (MainWindow window in GlobalSettings.Settings.MainWindows)
            {
                if (window.Trees != null && window.Trees.Count > 0)
                {
                    string targetFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".bin");

                    try
                    {
                        using (System.IO.FileStream fs = new System.IO.FileStream(targetFile, System.IO.FileMode.Create))
                        {
                            string tempFile = System.IO.Path.GetTempFileName();
                            using (System.IO.FileStream ms = new System.IO.FileStream(tempFile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                            {
                                using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms, System.Text.Encoding.UTF8, true))
                                {
                                    bw.Write((byte)0);
                                    bw.Write((byte)0);
                                    bw.Write((byte)0);
                                    bw.Write("#TreeViewer");
                                    bw.Write(window.SerializeAllModules(MainWindow.ModuleTarget.AllModules, true));

                                    bw.Write("#Attachments");
                                    bw.Write(window.StateData.Attachments.Count);

                                    foreach (KeyValuePair<string, Attachment> kvp in window.StateData.Attachments)
                                    {
                                        bw.Write(kvp.Key);
                                        bw.Write(2);
                                        bw.Write(kvp.Value.StoreInMemory);
                                        bw.Write(kvp.Value.CacheResults);
                                        bw.Write(kvp.Value.StreamLength);
                                        bw.Flush();

                                        kvp.Value.WriteToStream(ms);
                                    }

                                    bw.Flush();
                                    bw.Write(ms.Position - 3);
                                }

                                ms.Seek(0, System.IO.SeekOrigin.Begin);

                                PhyloTree.Formats.BinaryTree.WriteAllTrees(window.Trees, fs, additionalDataToCopy: ms);
                            }

                            System.IO.File.Delete(tempFile);
                        }

                        treeFiles.Add(targetFile);
                    }
                    catch
                    {

                    }
                }
            }

            return treeFiles;
        }

19 View Source File : MarkdownUtils.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

public static ImageRetrievalResult ImageUriResolverAsynchronous(string imageUri, string baseUriString, InstanceStateData stateData)
        {
            if (imageUri.Trim().StartsWith("circle://") || imageUri.Trim().StartsWith("ellipse://"))
            {
                try
                {
                    string[] parameters;

                    if (imageUri.Trim().StartsWith("circle://"))
                    {
                        parameters = imageUri.Trim().Substring(9).Split(',');
                    }
                    else
                    {
                        parameters = imageUri.Trim().Substring(10).Split(',');
                    }

                    double width;
                    double height;
                    double strokeThickness = 0;

                    Colour fill = Colour.FromRgba(0, 0, 0, 0);
                    Colour stroke = Colour.FromRgba(0, 0, 0, 0);

                    bool valid = false;

                    if (imageUri.Trim().StartsWith("circle://"))
                    {
                        valid = double.TryParse(parameters[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out width);
                        height = width;
                        if (parameters.Length > 2)
                        {
                            valid = valid && double.TryParse(parameters[2], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out strokeThickness);
                        }

                        fill = Colour.FromCSSString(parameters[1]) ?? Colour.FromRgba(0, 0, 0, 0);

                        if (parameters.Length > 3)
                        {
                            stroke = Colour.FromCSSString(parameters[3]) ?? Colour.FromRgba(0, 0, 0, 0);
                        }
                    }
                    else
                    {
                        valid = double.TryParse(parameters[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out width) & double.TryParse(parameters[1], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out height);

                        if (parameters.Length > 3)
                        {
                            valid = valid && double.TryParse(parameters[3], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out strokeThickness);
                        }

                        fill = Colour.FromCSSString(parameters[2]) ?? Colour.FromRgba(0, 0, 0, 0);

                        if (parameters.Length > 4)
                        {
                            stroke = Colour.FromCSSString(parameters[4]) ?? Colour.FromRgba(0, 0, 0, 0);
                        }
                    }

                    if (valid && width > 0 && height > 0 && (fill.A > 0 || stroke.A > 0))
                    {
                        VectSharp.Page pag = new Page(width + strokeThickness, height + strokeThickness);

                        double sqrt = Math.Sqrt(width * height);

                        pag.Graphics.Translate(pag.Width * 0.5, pag.Height * 0.5);
                        pag.Graphics.Scale(width / sqrt, height / sqrt);

                        GraphicsPath circle = new GraphicsPath().Arc(0, 0, sqrt * 0.5, 0, 2 * Math.PI).Close();

                        if (fill.A > 0)
                        {
                            pag.Graphics.FillPath(circle, fill);
                        }

                        if (stroke.A > 0)
                        {
                            pag.Graphics.StrokePath(circle, stroke, strokeThickness);
                        }

                        string path = Path.Combine(imageCacheFolder, System.Guid.NewGuid().ToString("N") + ".svg");

                        pag.SavereplacedVG(path);

                        return new ImageRetrievalResult(path, false);
                    }
                    else
                    {
                        return AsynchronousImageCache.ImageUriResolverAsynchronous(imageUri, baseUriString);
                    }
                }
                catch
                {
                    return AsynchronousImageCache.ImageUriResolverAsynchronous(imageUri, baseUriString);
                }
            }
            else if (imageUri.Trim().StartsWith("rect://") || imageUri.Trim().StartsWith("square://"))
            {
                try
                {
                    string[] parameters;

                    if (imageUri.Trim().StartsWith("rect://"))
                    {
                        parameters = imageUri.Trim().Substring(7).Split(',');
                    }
                    else
                    {
                        parameters = imageUri.Trim().Substring(9).Split(',');
                    }

                    double width;
                    double height;
                    double strokeThickness = 0;

                    Colour fill = Colour.FromRgba(0, 0, 0, 0);
                    Colour stroke = Colour.FromRgba(0, 0, 0, 0);

                    bool valid = false;

                    if (imageUri.Trim().StartsWith("square://"))
                    {
                        valid = double.TryParse(parameters[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out width);
                        height = width;
                        if (parameters.Length > 2)
                        {
                            valid = valid && double.TryParse(parameters[2], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out strokeThickness);
                        }

                        fill = Colour.FromCSSString(parameters[1]) ?? Colour.FromRgba(0, 0, 0, 0);

                        if (parameters.Length > 3)
                        {
                            stroke = Colour.FromCSSString(parameters[3]) ?? Colour.FromRgba(0, 0, 0, 0);
                        }
                    }
                    else
                    {
                        valid = double.TryParse(parameters[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out width) & double.TryParse(parameters[1], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out height);

                        if (parameters.Length > 3)
                        {
                            valid = valid && double.TryParse(parameters[3], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out strokeThickness);
                        }

                        fill = Colour.FromCSSString(parameters[2]) ?? Colour.FromRgba(0, 0, 0, 0);

                        if (parameters.Length > 4)
                        {
                            stroke = Colour.FromCSSString(parameters[4]) ?? Colour.FromRgba(0, 0, 0, 0);
                        }
                    }

                    if (valid && width > 0 && height > 0 && (fill.A > 0 || stroke.A > 0))
                    {
                        VectSharp.Page pag = new Page(width + strokeThickness, height + strokeThickness);

                        if (fill.A > 0)
                        {
                            pag.Graphics.FillRectangle(strokeThickness * 0.5, strokeThickness * 0.5, width, height, fill);
                        }

                        if (stroke.A > 0)
                        {
                            pag.Graphics.StrokeRectangle(strokeThickness * 0.5, strokeThickness * 0.5, width, height, stroke, strokeThickness);
                        }

                        string path = Path.Combine(imageCacheFolder, System.Guid.NewGuid().ToString("N") + ".svg");

                        pag.SavereplacedVG(path);

                        return new ImageRetrievalResult(path, false);
                    }
                    else
                    {
                        return AsynchronousImageCache.ImageUriResolverAsynchronous(imageUri, baseUriString);
                    }
                }
                catch
                {
                    return AsynchronousImageCache.ImageUriResolverAsynchronous(imageUri, baseUriString);
                }
            }
            else if (imageUri.Trim().StartsWith("poly://") || imageUri.Trim().StartsWith("star://"))
            {
                try
                {
                    bool isStar = imageUri.Trim().StartsWith("star://");

                    string[] parameters;

                    parameters = imageUri.Trim().Substring(7).Split(',');

                    double width;
                    double height;
                    double strokeThickness = 0;

                    Colour fill = Colour.FromRgba(0, 0, 0, 0);
                    Colour stroke = Colour.FromRgba(0, 0, 0, 0);

                    bool valid = false;

                    valid = double.TryParse(parameters[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out width);

                    int sides = isStar ? 5 : 3;

                    if (!double.TryParse(parameters[1], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out height))
                    {
                        height = width;
                        fill = Colour.FromCSSString(parameters[1]) ?? Colour.FromRgba(0, 0, 0, 0);

                        if (parameters.Length > 2)
                        {
                            valid = valid && int.TryParse(parameters[2], out sides);
                        }

                        if (parameters.Length > 3)
                        {
                            valid = valid && double.TryParse(parameters[3], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out strokeThickness);
                        }

                        if (parameters.Length > 4)
                        {
                            stroke = Colour.FromCSSString(parameters[4]) ?? Colour.FromRgba(0, 0, 0, 0);
                        }
                    }
                    else
                    {
                        fill = Colour.FromCSSString(parameters[2]) ?? Colour.FromRgba(0, 0, 0, 0);

                        if (parameters.Length > 3)
                        {
                            valid = valid && int.TryParse(parameters[3], out sides);
                        }

                        if (parameters.Length > 4)
                        {
                            valid = valid && double.TryParse(parameters[4], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out strokeThickness);
                        }

                        if (parameters.Length > 5)
                        {
                            stroke = Colour.FromCSSString(parameters[5]) ?? Colour.FromRgba(0, 0, 0, 0);
                        }
                    }


                    if (valid && width > 0 && height > 0 && (fill.A > 0 || stroke.A > 0) && sides > 2)
                    {
                        VectSharp.Page pag = new Page(width + strokeThickness, height + strokeThickness);

                        double sqrt = Math.Sqrt(width * height);

                        pag.Graphics.Translate(pag.Width * 0.5, pag.Height * 0.5);
                        pag.Graphics.Scale(width / sqrt, height / sqrt);

                        GraphicsPath polygon = new GraphicsPath();

                        polygon.MoveTo(sqrt * 0.5, 0);

                        if (!isStar)
                        {
                            double deltaAngle = Math.PI * 2 / sides;
                            for (int i = 1; i < sides; i++)
                            {
                                polygon.LineTo(Math.Cos(deltaAngle * i) * sqrt * 0.5, Math.Sin(deltaAngle * i) * sqrt * 0.5);
                            }
                        }
                        else
                        {
                            double deltaAngle = Math.PI / sides;
                            for (int i = 1; i < sides * 2; i++)
                            {
                                if (i % 2 == 0)
                                {
                                    polygon.LineTo(Math.Cos(deltaAngle * i) * sqrt * 0.5, Math.Sin(deltaAngle * i) * sqrt * 0.5);
                                }
                                else
                                {
                                    polygon.LineTo(Math.Cos(deltaAngle * i) * sqrt * 0.25, Math.Sin(deltaAngle * i) * sqrt * 0.25);
                                }
                            }
                        }

                        polygon.Close();

                        if (fill.A > 0)
                        {
                            pag.Graphics.FillPath(polygon, fill);
                        }

                        if (stroke.A > 0)
                        {
                            pag.Graphics.StrokePath(polygon, stroke, strokeThickness);
                        }

                        string path = Path.Combine(imageCacheFolder, System.Guid.NewGuid().ToString("N") + ".svg");

                        pag.SavereplacedVG(path);

                        return new ImageRetrievalResult(path, false);
                    }
                    else
                    {
                        return AsynchronousImageCache.ImageUriResolverAsynchronous(imageUri, baseUriString);
                    }
                }
                catch
                {
                    return AsynchronousImageCache.ImageUriResolverAsynchronous(imageUri, baseUriString);
                }
            }
            else if (imageUri.Trim().StartsWith("attachment://"))
            {
                try
                {
                    string attachmentName = imageUri.Trim().Substring(13);

                    if (stateData.Attachments.TryGetValue(attachmentName, out Attachment att))
                    {
                        string path = Path.Combine(imageCacheFolder, System.Guid.NewGuid().ToString("N"));

                        string extension;

                        using (FileStream fs = File.Create(path))
                        {
                            att.WriteToStream(fs);
                            fs.Seek(0, SeekOrigin.Begin);
                            extension = GetExtensionBasedOnContent(fs);
                        }
                        
                        if (!string.IsNullOrEmpty(extension))
                        {
                            File.Move(path, path + extension);
                            path = path + extension;
                        }

                        return new ImageRetrievalResult(path, false);

                    }
                    else
                    {
                        return AsynchronousImageCache.ImageUriResolverAsynchronous(imageUri, baseUriString);
                    }
                }
                catch
                {
                    return AsynchronousImageCache.ImageUriResolverAsynchronous(imageUri, baseUriString);
                }
            }
            else
            {
                return AsynchronousImageCache.ImageUriResolverAsynchronous(imageUri, baseUriString);
            }
        }

19 View Source File : MarkdownUtils.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

public static ImageRetrievalResult ImageUriResolverSynchronous(string imageUri, string baseUriString, InstanceStateData stateData)
        {
            if (imageUri.Trim().StartsWith("circle://") || imageUri.Trim().StartsWith("ellipse://"))
            {
                try
                {
                    string[] parameters;

                    if (imageUri.Trim().StartsWith("circle://"))
                    {
                        parameters = imageUri.Trim().Substring(9).Split(',');
                    }
                    else
                    {
                        parameters = imageUri.Trim().Substring(10).Split(',');
                    }

                    double width;
                    double height;
                    double strokeThickness = 0;

                    Colour fill = Colour.FromRgba(0, 0, 0, 0);
                    Colour stroke = Colour.FromRgba(0, 0, 0, 0);

                    bool valid = false;

                    if (imageUri.Trim().StartsWith("circle://"))
                    {
                        valid = double.TryParse(parameters[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out width);
                        height = width;
                        if (parameters.Length > 2)
                        {
                            valid = valid && double.TryParse(parameters[2], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out strokeThickness);
                        }

                        fill = Colour.FromCSSString(parameters[1]) ?? Colour.FromRgba(0, 0, 0, 0);

                        if (parameters.Length > 3)
                        {
                            stroke = Colour.FromCSSString(parameters[3]) ?? Colour.FromRgba(0, 0, 0, 0);
                        }
                    }
                    else
                    {
                        valid = double.TryParse(parameters[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out width) & double.TryParse(parameters[1], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out height);

                        if (parameters.Length > 3)
                        {
                            valid = valid && double.TryParse(parameters[3], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out strokeThickness);
                        }

                        fill = Colour.FromCSSString(parameters[2]) ?? Colour.FromRgba(0, 0, 0, 0);

                        if (parameters.Length > 4)
                        {
                            stroke = Colour.FromCSSString(parameters[4]) ?? Colour.FromRgba(0, 0, 0, 0);
                        }
                    }

                    if (valid && width > 0 && height > 0 && (fill.A > 0 || stroke.A > 0))
                    {
                        VectSharp.Page pag = new Page(width + strokeThickness, height + strokeThickness);

                        double sqrt = Math.Sqrt(width * height);

                        pag.Graphics.Translate(pag.Width * 0.5, pag.Height * 0.5);
                        pag.Graphics.Scale(width / sqrt, height / sqrt);

                        GraphicsPath circle = new GraphicsPath().Arc(0, 0, sqrt * 0.5, 0, 2 * Math.PI).Close();

                        if (fill.A > 0)
                        {
                            pag.Graphics.FillPath(circle, fill);
                        }

                        if (stroke.A > 0)
                        {
                            pag.Graphics.StrokePath(circle, stroke, strokeThickness);
                        }

                        string path = Path.Combine(imageCacheFolder, System.Guid.NewGuid().ToString("N") + ".svg");

                        pag.SavereplacedVG(path);

                        return new ImageRetrievalResult(path, false);
                    }
                    else
                    {
                        return AsynchronousImageCache.ImageUriResolverSynchronous(imageUri, baseUriString);
                    }
                }
                catch
                {
                    return AsynchronousImageCache.ImageUriResolverSynchronous(imageUri, baseUriString);
                }
            }
            else if (imageUri.Trim().StartsWith("rect://") || imageUri.Trim().StartsWith("square://"))
            {
                try
                {
                    string[] parameters;

                    if (imageUri.Trim().StartsWith("rect://"))
                    {
                        parameters = imageUri.Trim().Substring(7).Split(',');
                    }
                    else
                    {
                        parameters = imageUri.Trim().Substring(9).Split(',');
                    }

                    double width;
                    double height;
                    double strokeThickness = 0;

                    Colour fill = Colour.FromRgba(0, 0, 0, 0);
                    Colour stroke = Colour.FromRgba(0, 0, 0, 0);

                    bool valid = false;

                    if (imageUri.Trim().StartsWith("square://"))
                    {
                        valid = double.TryParse(parameters[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out width);
                        height = width;
                        if (parameters.Length > 2)
                        {
                            valid = valid && double.TryParse(parameters[2], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out strokeThickness);
                        }

                        fill = Colour.FromCSSString(parameters[1]) ?? Colour.FromRgba(0, 0, 0, 0);

                        if (parameters.Length > 3)
                        {
                            stroke = Colour.FromCSSString(parameters[3]) ?? Colour.FromRgba(0, 0, 0, 0);
                        }
                    }
                    else
                    {
                        valid = double.TryParse(parameters[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out width) & double.TryParse(parameters[1], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out height);

                        if (parameters.Length > 3)
                        {
                            valid = valid && double.TryParse(parameters[3], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out strokeThickness);
                        }

                        fill = Colour.FromCSSString(parameters[2]) ?? Colour.FromRgba(0, 0, 0, 0);

                        if (parameters.Length > 4)
                        {
                            stroke = Colour.FromCSSString(parameters[4]) ?? Colour.FromRgba(0, 0, 0, 0);
                        }
                    }

                    if (valid && width > 0 && height > 0 && (fill.A > 0 || stroke.A > 0))
                    {
                        VectSharp.Page pag = new Page(width + strokeThickness, height + strokeThickness);

                        if (fill.A > 0)
                        {
                            pag.Graphics.FillRectangle(strokeThickness * 0.5, strokeThickness * 0.5, width, height, fill);
                        }

                        if (stroke.A > 0)
                        {
                            pag.Graphics.StrokeRectangle(strokeThickness * 0.5, strokeThickness * 0.5, width, height, stroke, strokeThickness);
                        }

                        string path = Path.Combine(imageCacheFolder, System.Guid.NewGuid().ToString("N") + ".svg");

                        pag.SavereplacedVG(path);

                        return new ImageRetrievalResult(path, false);
                    }
                    else
                    {
                        return AsynchronousImageCache.ImageUriResolverSynchronous(imageUri, baseUriString);
                    }
                }
                catch
                {
                    return AsynchronousImageCache.ImageUriResolverSynchronous(imageUri, baseUriString);
                }
            }
            else if (imageUri.Trim().StartsWith("poly://") || imageUri.Trim().StartsWith("star://"))
            {
                try
                {
                    bool isStar = imageUri.Trim().StartsWith("star://");

                    string[] parameters;

                    parameters = imageUri.Trim().Substring(7).Split(',');

                    double width;
                    double height;
                    double strokeThickness = 0;

                    Colour fill = Colour.FromRgba(0, 0, 0, 0);
                    Colour stroke = Colour.FromRgba(0, 0, 0, 0);

                    bool valid = false;

                    valid = double.TryParse(parameters[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out width);

                    int sides = isStar ? 5 : 3;

                    if (!double.TryParse(parameters[1], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out height))
                    {
                        height = width;
                        fill = Colour.FromCSSString(parameters[1]) ?? Colour.FromRgba(0, 0, 0, 0);

                        if (parameters.Length > 2)
                        {
                            valid = valid && int.TryParse(parameters[2], out sides);
                        }

                        if (parameters.Length > 3)
                        {
                            valid = valid && double.TryParse(parameters[3], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out strokeThickness);
                        }

                        if (parameters.Length > 4)
                        {
                            stroke = Colour.FromCSSString(parameters[4]) ?? Colour.FromRgba(0, 0, 0, 0);
                        }
                    }
                    else
                    {
                        fill = Colour.FromCSSString(parameters[2]) ?? Colour.FromRgba(0, 0, 0, 0);

                        if (parameters.Length > 3)
                        {
                            valid = valid && int.TryParse(parameters[3], out sides);
                        }

                        if (parameters.Length > 4)
                        {
                            valid = valid && double.TryParse(parameters[4], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out strokeThickness);
                        }

                        if (parameters.Length > 5)
                        {
                            stroke = Colour.FromCSSString(parameters[5]) ?? Colour.FromRgba(0, 0, 0, 0);
                        }
                    }


                    if (valid && width > 0 && height > 0 && (fill.A > 0 || stroke.A > 0) && sides > 2)
                    {
                        VectSharp.Page pag = new Page(width + strokeThickness, height + strokeThickness);

                        double sqrt = Math.Sqrt(width * height);

                        pag.Graphics.Translate(pag.Width * 0.5, pag.Height * 0.5);
                        pag.Graphics.Scale(width / sqrt, height / sqrt);

                        GraphicsPath polygon = new GraphicsPath();

                        polygon.MoveTo(sqrt * 0.5, 0);

                        if (!isStar)
                        {
                            double deltaAngle = Math.PI * 2 / sides;
                            for (int i = 1; i < sides; i++)
                            {
                                polygon.LineTo(Math.Cos(deltaAngle * i) * sqrt * 0.5, Math.Sin(deltaAngle * i) * sqrt * 0.5);
                            }
                        }
                        else
                        {
                            double deltaAngle = Math.PI / sides;
                            for (int i = 1; i < sides * 2; i++)
                            {
                                if (i % 2 == 0)
                                {
                                    polygon.LineTo(Math.Cos(deltaAngle * i) * sqrt * 0.5, Math.Sin(deltaAngle * i) * sqrt * 0.5);
                                }
                                else
                                {
                                    polygon.LineTo(Math.Cos(deltaAngle * i) * sqrt * 0.25, Math.Sin(deltaAngle * i) * sqrt * 0.25);
                                }
                            }
                        }

                        polygon.Close();

                        if (fill.A > 0)
                        {
                            pag.Graphics.FillPath(polygon, fill);
                        }

                        if (stroke.A > 0)
                        {
                            pag.Graphics.StrokePath(polygon, stroke, strokeThickness);
                        }

                        string path = Path.Combine(imageCacheFolder, System.Guid.NewGuid().ToString("N") + ".svg");

                        pag.SavereplacedVG(path);

                        return new ImageRetrievalResult(path, false);
                    }
                    else
                    {
                        return AsynchronousImageCache.ImageUriResolverSynchronous(imageUri, baseUriString);
                    }
                }
                catch
                {
                    return AsynchronousImageCache.ImageUriResolverSynchronous(imageUri, baseUriString);
                }
            }
            else if (imageUri.Trim().StartsWith("attachment://"))
            {
                try
                {
                    string attachmentName = imageUri.Trim().Substring(13);

                    if (stateData.Attachments.TryGetValue(attachmentName, out Attachment att))
                    {
                        string path = Path.Combine(imageCacheFolder, System.Guid.NewGuid().ToString("N"));

                        string extension;

                        using (FileStream fs = File.Create(path))
                        {
                            att.WriteToStream(fs);
                            fs.Seek(0, SeekOrigin.Begin);
                            extension = GetExtensionBasedOnContent(fs);
                        }

                        if (!string.IsNullOrEmpty(extension))
                        {
                            File.Move(path, path + extension);
                            path = path + extension;
                        }

                        return new ImageRetrievalResult(path, false);

                    }
                    else
                    {
                        return AsynchronousImageCache.ImageUriResolverAsynchronous(imageUri, baseUriString);
                    }
                }
                catch
                {
                    return AsynchronousImageCache.ImageUriResolverAsynchronous(imageUri, baseUriString);
                }
            }
            else
            {
                return AsynchronousImageCache.ImageUriResolverSynchronous(imageUri, baseUriString);
            }
        }

19 View Source File : BinaryCommand.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

void ExportToStream(Stream stream, int subject, bool modules, bool addSignature, bool includeAttachments)
        {
            if (subject == 0)
            {
                if (modules)
                {
                    string tempFile = System.IO.Path.GetTempFileName();
                    using (System.IO.FileStream ms = new System.IO.FileStream(tempFile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                    {
                        using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms, System.Text.Encoding.UTF8, true))
                        {
                            bw.Write((byte)0);
                            bw.Write((byte)0);
                            bw.Write((byte)0);
                            bw.Write("#TreeViewer");
                            bw.Write(Program.SerializeAllModules(MainWindow.ModuleTarget.AllModules, addSignature));

                            if (includeAttachments)
                            {
                                bw.Write("#Attachments");
                                bw.Write(Program.StateData.Attachments.Count);

                                foreach (KeyValuePair<string, Attachment> kvp in Program.StateData.Attachments)
                                {
                                    bw.Write(kvp.Key);
                                    bw.Write(2);
                                    bw.Write(kvp.Value.StoreInMemory);
                                    bw.Write(kvp.Value.CacheResults);
                                    bw.Write(kvp.Value.StreamLength);
                                    bw.Flush();

                                    kvp.Value.WriteToStream(ms);
                                }
                            }

                            bw.Flush();
                            bw.Write(ms.Position - 3);
                        }

                        ms.Seek(0, System.IO.SeekOrigin.Begin);

                        BinaryTree.WriteAllTrees(Program.Trees, stream, additionalDataToCopy: ms);
                    }

                    System.IO.File.Delete(tempFile);
                }
                else
                {
                    if (!includeAttachments)
                    {
                        BinaryTree.WriteAllTrees(Program.Trees, stream);
                    }
                    else
                    {
                        string tempFile = System.IO.Path.GetTempFileName();
                        using (System.IO.FileStream ms = new System.IO.FileStream(tempFile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                        {
                            using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms, System.Text.Encoding.UTF8, true))
                            {
                                bw.Write((byte)0);
                                bw.Write((byte)0);
                                bw.Write((byte)0);
                                bw.Write("#Attachments");
                                bw.Write(Program.StateData.Attachments.Count);

                                foreach (KeyValuePair<string, Attachment> kvp in Program.StateData.Attachments)
                                {
                                    bw.Write(kvp.Key);
                                    bw.Write(2);
                                    bw.Write(kvp.Value.StoreInMemory);
                                    bw.Write(kvp.Value.CacheResults);
                                    bw.Write(kvp.Value.StreamLength);
                                    bw.Flush();

                                    kvp.Value.WriteToStream(ms);
                                }

                                bw.Flush();
                                bw.Write(ms.Position - 3);
                            }

                            ms.Seek(0, System.IO.SeekOrigin.Begin);

                            BinaryTree.WriteAllTrees(Program.Trees, stream, additionalDataToCopy: ms);
                        }

                        System.IO.File.Delete(tempFile);
                    }
                }
            }
            else if (subject == 1)
            {
                if (modules)
                {
                    string tempFile = System.IO.Path.GetTempFileName();
                    using (System.IO.FileStream ms = new System.IO.FileStream(tempFile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                    {
                        using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms, System.Text.Encoding.UTF8, true))
                        {
                            bw.Write((byte)0);
                            bw.Write((byte)0);
                            bw.Write((byte)0);
                            bw.Write("#TreeViewer");
                            bw.Write(Program.SerializeAllModules(MainWindow.ModuleTarget.ExcludeTransform, addSignature));

                            if (includeAttachments)
                            {
                                bw.Write("#Attachments");
                                bw.Write(Program.StateData.Attachments.Count);

                                foreach (KeyValuePair<string, Attachment> kvp in Program.StateData.Attachments)
                                {
                                    bw.Write(kvp.Key);
                                    bw.Write(2);
                                    bw.Write(kvp.Value.StoreInMemory);
                                    bw.Write(kvp.Value.CacheResults);
                                    bw.Write(kvp.Value.StreamLength);
                                    bw.Flush();

                                    kvp.Value.WriteToStream(ms);
                                }
                            }

                            bw.Flush();
                            bw.Write(ms.Position - 3);
                        }

                        ms.Seek(0, System.IO.SeekOrigin.Begin);

                        BinaryTree.WriteAllTrees(new TreeNode[] { Program.FirstTransformedTree }, stream, additionalDataToCopy: ms);
                    }
                    System.IO.File.Delete(tempFile);
                }
                else
                {
                    if (!includeAttachments)
                    {
                        BinaryTree.WriteAllTrees(new TreeNode[] { Program.FirstTransformedTree }, stream);
                    }
                    else
                    {

                        string tempFile = System.IO.Path.GetTempFileName();
                        using (System.IO.FileStream ms = new System.IO.FileStream(tempFile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                        {
                            using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms, System.Text.Encoding.UTF8, true))
                            {
                                bw.Write((byte)0);
                                bw.Write((byte)0);
                                bw.Write((byte)0);
                                bw.Write("#Attachments");
                                bw.Write(Program.StateData.Attachments.Count);

                                foreach (KeyValuePair<string, Attachment> kvp in Program.StateData.Attachments)
                                {
                                    bw.Write(kvp.Key);
                                    bw.Write(2);
                                    bw.Write(kvp.Value.StoreInMemory);
                                    bw.Write(kvp.Value.CacheResults);
                                    bw.Write(kvp.Value.StreamLength);
                                    bw.Flush();

                                    kvp.Value.WriteToStream(ms);
                                }

                                bw.Flush();
                                bw.Write(ms.Position - 3);
                            }

                            ms.Seek(0, System.IO.SeekOrigin.Begin);

                            BinaryTree.WriteAllTrees(new TreeNode[] { Program.FirstTransformedTree }, stream, additionalDataToCopy: ms);
                        }

                        System.IO.File.Delete(tempFile);
                    }
                }
            }
            else if (subject == 2)
            {
                if (modules)
                {
                    string tempFile = System.IO.Path.GetTempFileName();
                    using (System.IO.FileStream ms = new System.IO.FileStream(tempFile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                    {
                        using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms, System.Text.Encoding.UTF8, true))
                        {
                            bw.Write((byte)0);
                            bw.Write((byte)0);
                            bw.Write((byte)0);
                            bw.Write("#TreeViewer");
                            bw.Write(Program.SerializeAllModules(MainWindow.ModuleTarget.ExcludeFurtherTransformation, addSignature));

                            if (includeAttachments)
                            {
                                bw.Write("#Attachments");
                                bw.Write(Program.StateData.Attachments.Count);

                                foreach (KeyValuePair<string, Attachment> kvp in Program.StateData.Attachments)
                                {
                                    bw.Write(kvp.Key);
                                    bw.Write(2);
                                    bw.Write(kvp.Value.StoreInMemory);
                                    bw.Write(kvp.Value.CacheResults);
                                    bw.Write(kvp.Value.StreamLength);
                                    bw.Flush();

                                    kvp.Value.WriteToStream(ms);
                                }
                            }

                            bw.Flush();
                            bw.Write(ms.Position - 3);
                        }

                        ms.Seek(0, System.IO.SeekOrigin.Begin);

                        BinaryTree.WriteAllTrees(new TreeNode[] { Program.TransformedTree }, stream, additionalDataToCopy: ms);
                    }

                    System.IO.File.Delete(tempFile);
                }
                else
                {
                    if (!includeAttachments)
                    {
                        BinaryTree.WriteAllTrees(new TreeNode[] { Program.TransformedTree }, stream);
                    }
                    else
                    {

                        string tempFile = System.IO.Path.GetTempFileName();
                        using (System.IO.FileStream ms = new System.IO.FileStream(tempFile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                        {
                            using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms, System.Text.Encoding.UTF8, true))
                            {
                                bw.Write((byte)0);
                                bw.Write((byte)0);
                                bw.Write((byte)0);
                                bw.Write("#Attachments");
                                bw.Write(Program.StateData.Attachments.Count);

                                foreach (KeyValuePair<string, Attachment> kvp in Program.StateData.Attachments)
                                {
                                    bw.Write(kvp.Key);
                                    bw.Write(2);
                                    bw.Write(kvp.Value.StoreInMemory);
                                    bw.Write(kvp.Value.CacheResults);
                                    bw.Write(kvp.Value.StreamLength);
                                    bw.Flush();

                                    kvp.Value.WriteToStream(ms);
                                }

                                bw.Flush();
                                bw.Write(ms.Position - 3);
                            }

                            ms.Seek(0, System.IO.SeekOrigin.Begin);

                            BinaryTree.WriteAllTrees(new TreeNode[] { Program.TransformedTree }, stream, additionalDataToCopy: ms);
                        }

                        System.IO.File.Delete(tempFile);
                    }
                }
            }
        }

19 View Source File : HtmlTag.cs
License : GNU General Public License v3.0
Project Creator : arklumpus

private static string FixFileExtensionBasedOnContent(string fileName)
        {
            using (FileStream fileStream = File.OpenRead(fileName))
            {
                bool isSvg = false;

                try
                {
                    using (var xmlReader = System.Xml.XmlReader.Create(fileStream))
                    {
                        isSvg = xmlReader.MoveToContent() == System.Xml.XmlNodeType.Element && "svg".Equals(xmlReader.Name, StringComparison.OrdinalIgnoreCase);
                    }
                }
                catch
                {
                    isSvg = false;
                }

                if (isSvg)
                {
                    return fileName + ".svg";
                }
                else
                {
                    fileStream.Seek(0, SeekOrigin.Begin);
                    byte[] header = new byte[8];

                    for (int i = 0; i < header.Length; i++)
                    {
                        header[i] = (byte)fileStream.ReadByte();
                    }

                    if (header[0] == 0x42 && header[1] == 0x4D)
                    {
                        return fileName + ".bmp";
                    }
                    else if (header[0] == 0x47 && header[1] == 0x49 && header[2] == 0x46 && header[3] == 0x38)
                    {
                        return fileName + ".gif";
                    }
                    else if (header[0] == 0xFF && header[1] == 0xD8 && header[2] == 0xFF && (header[3] == 0xDB || header[3] == 0xE0 || header[3] == 0xEE || header[3] == 0xE1))
                    {
                        return fileName + ".jpg";
                    }
                    else if (header[0] == 0x25 && header[1] == 0x50 && header[2] == 0x44 && header[3] == 0x46 && header[4] == 0x2D)
                    {
                        return fileName + ".pdf";
                    }
                    else if (header[0] == 0x89 && header[1] == 0x50 && header[2] == 0x4E && header[3] == 0x47 && header[4] == 0x0D && header[5] == 0x0A && header[6] == 0x1A && header[7] == 0x0A)
                    {
                        return fileName + ".png";
                    }
                    else if ((header[0] == 0x49 && header[1] == 0x49 && header[2] == 0x2A && header[3] == 0x00) || (header[0] == 0x4D && header[1] == 0x4D && header[2] == 0x00 && header[3] == 0x2A))
                    {
                        return fileName + ".tif";
                    }
                    else
                    {
                        return fileName;
                    }
                }
            }
        }

19 View Source File : InternalLogger.cs
License : MIT License
Project Creator : askguanyu

private static void AppendToFile(string message)
        {
            try
            {
            }
            finally
            {
                FileStream fileStream = null;

                try
                {
                    fileStream = new FileStream(LogFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete);

                    if (fileStream.Length > 10485760)
                    {
                        try
                        {
                            File.Copy(LogFile, LogFileBackup, true);
                        }
                        catch
                        {
                        }

                        fileStream.SetLength(0);
                    }

                    byte[] bytes = Encoding.UTF8.GetBytes(message);

                    fileStream.Seek(0, SeekOrigin.End);
                    fileStream.Write(bytes, 0, bytes.Length);
                    fileStream.Flush();
                }
                catch
                {
                }
                finally
                {
                    if (fileStream != null)
                    {
                        fileStream.Dispose();
                        fileStream = null;
                    }
                }
            }
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : Assistant

public static string GetVersion()
        {
            string filename = Path.Combine(App.BeatSaberInstallDirectory, "Beat Saber_Data", "globalgamemanagers");
            using (var stream = File.OpenRead(filename))
            using (var reader = new BinaryReader(stream, Encoding.UTF8))
            {
                const string key = "public.app-category.games";
                int pos = 0;

                while (stream.Position < stream.Length && pos < key.Length)
                {
                    if (reader.ReadByte() == key[pos]) pos++;
                    else pos = 0;
                }

                if (stream.Position == stream.Length) // we went through the entire stream without finding the key
                    return null;

                while (stream.Position < stream.Length)
                {
                    var current = (char)reader.ReadByte();
                    if (char.IsDigit(current))
                        break;
                }

                var rewind = -sizeof(int) - sizeof(byte);
                stream.Seek(rewind, SeekOrigin.Current); // rewind to the string length

                var strlen = reader.ReadInt32();
                var strbytes = reader.ReadBytes(strlen);

                return Encoding.UTF8.GetString(strbytes);
            }
        }

19 View Source File : AnalyzeTask.cs
License : GNU General Public License v3.0
Project Creator : AtomCrafty

protected override void Execute() {
			if(arguments.Length == 0) Fail("No source file specified");

			string sourceBasePath = Helpers.AbsolutePath(arguments[0]);
			string targetBasePath = arguments.Length > 1 ? Helpers.AbsolutePath(arguments[1]) : Path.ChangeExtension(sourceBasePath, Constants.html);

			string[] files = null;
			if(Directory.Exists(sourceBasePath)) {
				files = Directory.GetFileSystemEntries(sourceBasePath, "*", SearchOption.AllDirectories);

				// TODO replacedyze directory
			}
			else if(File.Exists(sourceBasePath)) {
				string ext = Path.GetExtension(sourceBasePath).ToLower();

				// Binary script
				if(ext.Equals('.' + Constants.yks)) {
					FileStream fs = new FileStream(sourceBasePath, FileMode.Open);
					BinaryReader r = new BinaryReader(fs);

					// read header
					var report = new replacedyzerReport.ScriptBinary() {
						Magic = r.ReadBytes(6),
						Version = r.ReadInt16(),
						HeaderSize = r.ReadInt32(),
						Unknown1 = r.ReadInt32(),
						CodeOffset = r.ReadInt32(),
						CodeCount = r.ReadInt32(),
						IndexOffset = r.ReadInt32(),
						IndexCount = r.ReadInt32(),
						DataOffset = r.ReadInt32(),
						DataLength = r.ReadInt32(),
						VarPoolSize = r.ReadInt32(),
						Unknown2 = r.ReadInt32()
					};

					// read data
					var data = new byte[report.DataLength];
					fs.Seek(report.DataOffset, SeekOrigin.Begin);
					for(int i = 0; i < report.DataLength; i++) {
						data[i] = (byte)(r.ReadByte() ^ 0xAA);
					}

					// read index
					fs.Seek(report.IndexOffset, SeekOrigin.Begin);
					report.Index = new replacedyzerReport.ScriptBinary.IndexEntry[report.IndexCount];
					for(int i = 0; i < report.IndexCount; i++) {
						var entry = new replacedyzerReport.ScriptBinary.IndexEntry(i, r.ReadInt32(), r.ReadInt32(), r.ReadInt32(), r.ReadInt32());
						report.Index[i] = entry;
					}

					// read code
					var code = new List<replacedyzerReport.ScriptBinary.CodeEntry>();
					int maxArgs = 0;
					fs.Seek(report.CodeOffset, SeekOrigin.Begin);
					for(int i = 0; i < report.CodeCount; i++) {
						int instrID = r.ReadInt32();
						var instruction = (instrID >= 0 && instrID < report.Index.Length) ? report.Index[instrID] : new replacedyzerReport.ScriptBinary.IndexEntry(instrID, -1, -1, -1, -1);
						if(instruction.Type == replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_FUNC) {
							int argCount = r.ReadInt32();
							if(argCount > maxArgs) maxArgs = argCount;
							i += argCount + 1;
							var arguments = new replacedyzerReport.ScriptBinary.IndexEntry[argCount];
							for(int j = 0; j < argCount; j++) {
								int argID = r.ReadInt32();
								arguments[j] = (argID >= 0 && argID < report.Index.Length) ? report.Index[argID] : new replacedyzerReport.ScriptBinary.IndexEntry(argID, -1, -1, -1, -1);
							}
							code.Add(new replacedyzerReport.ScriptBinary.CodeEntry(i, instruction, arguments));
						}
						else {
							code.Add(new replacedyzerReport.ScriptBinary.CodeEntry(i, instruction));
						}
					}
					report.Code = code.ToArray();





					var w = StartOutput(targetBasePath);
					{
						StartSection("Meta Information", w);
						{
							Echo("File Name:			" + Path.GetFileName(sourceBasePath) + '\n', w);
							Echo("File Type:			Compiled Yuka Script (.yks)\n", w);
							Echo("File Size:			" + new FileInfo(sourceBasePath).Length + " bytes\n", w);
						}
						FinishSection(w);

						StartSection("File Header", w);
						{
							Echo("Magic:				", w);
							Echo(BitConverter.ToString(report.Magic).Replace('-', ' '), " ", "const const-str", w);
							Echo("# ", "comment", w);
							Echo('"' + Encoding.ASCII.GetString(report.Magic) + '"', "\n", "const const-str", w);

							Echo("Version:			", w);
							Echo(report.Version.ToString("X4"), "              ", "const const-int", w);
							Echo("# ", "comment", w);
							Echo(report.Version.ToString(), "\n", "const const-int", w);

							Echo("HeaderSize:			", w);
							Echo(report.HeaderSize.ToString("X8"), "          ", "const const-int", w);
							Echo("# ", "comment", w);
							Echo(report.HeaderSize.ToString(), "\n", "const const-int", w);

							Echo("?:					", w);
							Echo(report.Unknown1.ToString("X8"), "          ", "const const-int", w);
							Echo("# ", "comment", w);
							Echo(report.Unknown1.ToString(), "\n", "const const-int", w);

							Echo("Code Offset:		", w);
							Echo(report.CodeOffset.ToString("X8"), "          ", "const const-int", w);
							Echo("# ", "comment", w);
							Echo(report.CodeOffset.ToString(), "\n", "const const-int", w);

							Echo("Instruction Count:	", w);
							Echo(report.CodeCount.ToString("X8"), "          ", "const const-int", w);
							Echo("# ", "comment", w);
							Echo(report.CodeCount.ToString(), "\n", "const const-int", w);

							Echo("Index Offset:		", w);
							Echo(report.IndexOffset.ToString("X8"), "          ", "const const-int", w);
							Echo("# ", "comment", w);
							Echo(report.IndexOffset.ToString(), "\n", "const const-int", w);

							Echo("Entry Count:		", w);
							Echo(report.IndexCount.ToString("X8"), "          ", "const const-int", w);
							Echo("# ", "comment", w);
							Echo(report.IndexCount.ToString(), "\n", "const const-int", w);

							Echo("Data Offset:		", w);
							Echo(report.DataOffset.ToString("X8"), "          ", "const const-int", w);
							Echo("# ", "comment", w);
							Echo(report.DataOffset.ToString(), "\n", "const const-int", w);

							Echo("Data Lentgh:		", w);
							Echo(report.DataLength.ToString("X8"), "          ", "const const-int", w);
							Echo("# ", "comment", w);
							Echo(report.DataLength.ToString(), "\n", "const const-int", w);

							Echo("Var Pool Size:		", w);
							Echo(report.VarPoolSize.ToString("X8"), "          ", "const const-int", w);
							Echo("# ", "comment", w);
							Echo(report.VarPoolSize.ToString(), "\n", "const const-int", w);

							Echo("?:					", w);
							Echo(report.Unknown2.ToString("X8"), "          ", "const const-int", w);
							Echo("# ", "comment", w);
							Echo(report.Unknown2.ToString(), "\n", "const const-int", w);
						}
						FinishSection(w);

						StartSection("Code", w);
						{
							Echo(maxArgs == 0
								? "          Function" : maxArgs == 1
								? "          Function ArgCount Argument"
								: "          Function ArgCount |---Arguments---" + new string('-', maxArgs * 9 - 18) + "|\n", w);
							foreach(var instr in report.Code) {
								Echo(instr.Address.ToString("X8"), ": ", "address", w);
								switch(instr.Instruction.Type) {
									case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_FUNC:
										Echo(instr.Instruction.ID.ToString("X8"), " ", "ref ref-fnc", w);
										Echo(instr.Arguments.Length.ToString("X8"), " ", "const const-int", w);
										foreach(var arg in instr.Arguments) {
											switch(arg.Type) {
												case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_FUNC:
													Echo(arg.ID.ToString("X8"), " ", "ref ref-fnc", w);
													break;
												case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_CTRL:
													Echo(arg.ID.ToString("X8"), " ", "ref ref-lbl", w);
													break;
												case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_CINT:
													Echo(arg.ID.ToString("X8"), " ", "ref ref-int", w);
													break;
												case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_CSTR:
													Echo(arg.ID.ToString("X8"), " ", "ref ref-str", w);
													break;
												case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_VINT:
												case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_VSTR:
												case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_VTMP:
													Echo(arg.ID.ToString("X8"), " ", "ref ref-var", w);
													break;
												default:
													Echo(arg.ID.ToString("X8"), " ", "ref", w);
													break;
											}
										}
										Echo(new string(' ', (maxArgs - instr.Arguments.Length) * 9), "", w);
										Echo("# ", "comment", w);
										Echo(Helpers.ToZeroTerminatedString(data, instr.Instruction.Field1), "src src-fnc", w);
										Echo("(", "comment", w);
										bool flag = false;
										foreach(var arg in instr.Arguments) {
											if(flag) {
												Echo(", ", "comment", w);
											}
											switch(arg.Type) {
												case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_FUNC:
													Echo("&" + Helpers.ToZeroTerminatedString(data, arg.Field1), "src src-fnc", w);
													break;
												case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_CTRL:
													Echo(":" + Helpers.ToZeroTerminatedString(data, arg.Field1), "src src-lbl", w);
													break;
												case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_CINT:
													Echo(BitConverter.ToInt32(data, arg.Field2).ToString(), "src src-int", w);
													break;
												case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_CSTR:
													Echo('"' + Helpers.ToZeroTerminatedString(data, arg.Field2) + '"', "src src-str", w);
													break;
												case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_VINT:
												case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_VSTR:
													Echo(Helpers.ToZeroTerminatedString(data, arg.Field1) + ':' + BitConverter.ToInt32(data, arg.Field3), "src src-var", w);
													break;
												case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_VTMP:
													Echo('$' + arg.Field2.ToString(), "src src-var", w);
													break;
												default:
													Echo(arg.ID.ToString(), "src", w);
													break;
											}
											flag = true;
										}
										Echo(")", "\n", "comment", w);
										break;
									case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_CTRL:
										Echo(instr.Instruction.ID.ToString("X8"), " ", "ref ref-lbl", w);
										Echo(new string(' ', (maxArgs + 1) * 9), w);
										Echo("# ", "comment", w);
										Echo(":" + Helpers.ToZeroTerminatedString(data, instr.Instruction.Field1), "\n", "src src-lbl", w);
										break;
									case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_CINT:
										Echo(instr.Instruction.ID.ToString("X8"), " ", "ref ref-int", w);
										Echo(new string(' ', (maxArgs + 1) * 9), w);
										Echo("# ", "comment", w);
										Echo(instr.Instruction.ID.ToString(), "\n", "src src-int", w);
										break;
									case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_CSTR:
										Echo(instr.Instruction.ID.ToString("X8"), " ", "ref ref-str", w);
										Echo(new string(' ', (maxArgs + 1) * 9), w);
										Echo("# ", "comment", w);
										Echo('"' + Helpers.ToZeroTerminatedString(data, instr.Instruction.Field2) + '"', "\n", "src src-str", w);
										break;
									case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_VINT:
									case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_VSTR:
										Echo(instr.Instruction.ID.ToString("X8"), " ", "ref ref-var", w);
										Echo(new string(' ', (maxArgs + 1) * 9), w);
										Echo("# ", "comment", w);
										Echo(Helpers.ToZeroTerminatedString(data, instr.Instruction.Field1) + ':' + BitConverter.ToInt32(data, instr.Instruction.Field3), "\n", "src src-var", w);
										break;
									case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_VTMP:
										Echo(instr.Instruction.ID.ToString("X8"), " ", "ref ref-var", w);
										Echo(new string(' ', (maxArgs + 1) * 9), w);
										Echo("# ", "comment", w);
										Echo('$' + instr.Instruction.Field2.ToString(), "\n", "src src-var", w);
										break;
									default:
										Echo(instr.Instruction.ID.ToString("X8"), " ", "ref", w);
										Echo(new string(' ', (maxArgs + 1) * 9), w);
										Echo("# ", "comment", w);
										Echo(instr.Instruction.ID.ToString(), "\n", "src", w);
										break;
								}
							}
						}
						FinishSection(w);

						StartSection("Index", w);
						{
							foreach(var entry in report.Index) {
								switch(entry.Type) {
									case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_FUNC:
										Echo(entry.ID.ToString("X8"), ": ", "address", w);
										Echo("YKS_FUNC", " ", "type type-func", w);
										Echo(entry.Field1.ToString("X8"), " ", "ref ref-str", w);
										Echo(entry.Field2.ToString("X8"), " ", "const const-int", w);
										Echo(entry.Field3.ToString("X8"), " ", "unused", w);
										Echo("# function ", "comment", w);
										Echo("\"" + Helpers.ToZeroTerminatedString(data, entry.Field1) + "\"", "const const-str", w);
										Echo(", last used at ", "comment", w);
										Echo(entry.Field2.ToString("X8"), "\n", "const, const-int", w);
										break;
									case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_CTRL:
										Echo(entry.ID.ToString("X8"), ": ", "address", w);
										Echo("YKS_CTRL", " ", "type type-ctrl", w);
										Echo(entry.Field1.ToString("X8"), " ", "ref ref-str", w);
										Echo(entry.Field2.ToString("X8"), " ", "ref ref-int", w);
										Echo(entry.Field3.ToString("X8"), " ", "unused", w);
										Echo("# jump label ", "comment", w);
										Echo("\"" + Helpers.ToZeroTerminatedString(data, entry.Field1) + "\"", "const const-str", w);
										Echo(", linked to ", "comment", w);
										Echo(BitConverter.ToInt32(data, entry.Field2).ToString("X8"), "\n", "const, const-int", w);
										break;
									case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_CINT:
										Echo(entry.ID.ToString("X8"), ": ", "address", w);
										Echo("YKS_CINT", " ", "type type-cint", w);
										Echo(entry.Field1.ToString("X8"), " ", "unused", w);
										Echo(entry.Field2.ToString("X8"), " ", "ref ref-int", w);
										Echo(entry.Field3.ToString("X8"), " ", "unused", w);
										Echo("# integer constant: ", "comment", w);
										Echo(BitConverter.ToInt32(data, entry.Field2).ToString(), "const const-int", w);
										Echo(" (", "comment", w);
										Echo("0x" + BitConverter.ToInt32(data, entry.Field2).ToString("X"), "const const-int", w);
										Echo(")", "\n", "comment", w);
										break;
									case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_CSTR:
										Echo(entry.ID.ToString("X8"), ": ", "address", w);
										Echo("YKS_CSTR", " ", "type type-cstr", w);
										Echo(entry.Field1.ToString("X8"), " ", "unused", w);
										Echo(entry.Field2.ToString("X8"), " ", "ref ref-str", w);
										Echo(entry.Field3.ToString("X8"), " ", "unused", w);
										Echo("# string constant: ", "comment", w);
										Echo("\"" + Helpers.ToZeroTerminatedString(data, entry.Field2) + "\"", "\n", "const const-str", w);
										break;
									case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_VINT:
										Echo(entry.ID.ToString("X8"), ": ", "address", w);
										Echo("YKS_VINT", " ", "type type-vint", w);
										Echo(entry.Field1.ToString("X8"), " ", "ref ref-str", w);
										Echo(entry.Field2.ToString("X8"), " ", "unused", w);
										Echo(entry.Field3.ToString("X8"), " ", "ref ref-int", w);
										Echo("# integer variable: ", "comment", w);
										Echo(Helpers.ToZeroTerminatedString(data, entry.Field1), "const const-str", w);
										Echo("[", "comment", w);
										Echo(BitConverter.ToInt32(data, entry.Field3).ToString(), "const, const-int", w);
										Echo("]", "\n", "comment", w);
										break;
									case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_VSTR:
										Echo(entry.ID.ToString("X8"), ": ", "address", w);
										Echo("YKS_VSTR", " ", "type type-vstr", w);
										Echo(entry.Field1.ToString("X8"), " ", "ref ref-str", w);
										Echo(entry.Field2.ToString("X8"), " ", "unused", w);
										Echo(entry.Field3.ToString("X8"), " ", "ref ref-int", w);
										Echo("# string variable: ", "comment", w);
										Echo(Helpers.ToZeroTerminatedString(data, entry.Field1), "const const-str", w);
										Echo("[", "comment", w);
										Echo(BitConverter.ToInt32(data, entry.Field3).ToString(), "const, const-int", w);
										Echo("]", "\n", "comment", w);
										break;
									case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_VTMP:
										Echo(entry.ID.ToString("X8"), ": ", "address", w);
										Echo("YKS_VTMP", " ", "type type-vtmp", w);
										Echo(entry.Field1.ToString("X8"), " ", "unused", w);
										Echo(entry.Field2.ToString("X8"), " ", "ref ref-int", w);
										Echo(entry.Field3.ToString("X8"), " ", "unused", w);
										Echo("# temporary variable: $", "comment", w);
										Echo(entry.Field2.ToString(), "\n", "const, const-int", w);
										break;
									default:
										Echo(entry.ID.ToString("X8"), ": ", "address", w);
										Echo(entry.Type.ToString("X"), " ", "type type-unknown", w);
										Echo(entry.Field1.ToString("X8"), " ", "unused", w);
										Echo(entry.Field2.ToString("X8"), " ", "unused", w);
										Echo(entry.Field3.ToString("X8"), " ", "unused", w);
										Echo("#", "\n", "comment", w);
										break;
								}
							}
						}
						FinishSection(w);

						StartSection("Data", w);
						{
							int offset = 0;
							while(offset < data.Length) {
								bool isInt = false, isString = false;
								foreach(var entry in report.Index) {
									switch(entry.Type) {
										case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_FUNC:
											if(entry.Field1 == offset) isString = true;
											break;
										case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_CTRL:
											if(entry.Field1 == offset) isString = true;
											if(entry.Field2 == offset) isInt = true;
											break;
										case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_CINT:
											if(entry.Field2 == offset) isInt = true;
											break;
										case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_CSTR:
											if(entry.Field2 == offset) isString = true;
											break;
										case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_VINT:
											if(entry.Field1 == offset) isString = true;
											if(entry.Field3 == offset) isInt = true;
											break;
										case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_VSTR:
											if(entry.Field1 == offset) isString = true;
											if(entry.Field3 == offset) isInt = true;
											break;
										case replacedyzerReport.ScriptBinary.IndexEntry.EntryType.YKS_VTMP:
										default:
											break;
									}
								}
								if(isInt) {
									int res = BitConverter.ToInt32(data, offset);
									Echo(offset.ToString("X8"), ": ", "address", w);
									Echo(res.ToString("X8"), " ", "const const-int", w);
									Echo("(", res.ToString(), ")\n", "const const-int", w);
									offset += 4;
								}
								else if(isString) {
									string res = Helpers.ToZeroTerminatedString(data, offset);
									byte[] bytes = Encoding.GetEncoding("Shift-JIS").GetBytes(res);
									Echo(offset.ToString("X8"), ": ", "address", w);
									Echo(BitConverter.ToString(bytes).Replace('-', ' ') + " 00", " ", "const const-str", w);
									Echo("(", '"' + res + '"', ")\n", "const const-str", w);
									offset += bytes.Length + 1;
								}
								else {
									Echo("Data sector replacedysis failed.\n", "error", w);
									break;
								}
							}
						}
						FinishSection(w);
					}
					FinishOutput(w);
				}
				else {
					Console.WriteLine("At this point in time only compiled scripts can be replacedyzed.");
				}

				// TODO replacedyze other file types
			}
			else {
				Fail("The specified source file does not exist");
			}
			currentFile = "";
			if(flags.Has('w')) {
				Console.ReadLine();
			}
		}

19 View Source File : SplitTask.cs
License : GNU General Public License v3.0
Project Creator : AtomCrafty

protected override void Execute() {
			if(arguments.Length == 0) Fail("No source file specified");

			string sourcePath = Helpers.AbsolutePath(arguments[0]);
			string targetPath = arguments.Length > 1 ? Helpers.AbsolutePath(arguments[1]) : sourcePath;

			if(!System.IO.File.Exists(sourcePath)) Fail("File does not exist");

			FileStream fs = new FileStream(sourcePath, FileMode.Open);
			FileStream os;
			BinaryReader br = new BinaryReader(fs);
			{
				fs.Seek(0x10, SeekOrigin.Begin);
				int codeoffset = br.ReadInt32();
				int codecount = br.ReadInt32();
				int indexoffset = br.ReadInt32();
				int indexcount = br.ReadInt32();
				int dataoffset = br.ReadInt32();
				int datalength = br.ReadInt32();

				// code binary (+ header)
				os = new FileStream(Path.ChangeExtension(targetPath, ".code.dat"), FileMode.Create);
				fs.Seek(0, SeekOrigin.Begin);
				Helpers.CopyStream(fs, os, codecount * 4);

				// code ascii
				os = new FileStream(Path.ChangeExtension(targetPath, ".code.txt"), FileMode.Create);
				fs.Seek(codeoffset, SeekOrigin.Begin);
				os.WriteByte((byte)'\n');
				for(int i = 0; i < codecount; i++) {
					int commandID = br.ReadInt32();
					StringBuilder sb = new StringBuilder(commandID.ToString("X8"));

					// fetch cmd type from index
					long cpos = fs.Position;
					fs.Seek(indexoffset + commandID * 16, SeekOrigin.Begin);
					int cmdType = br.ReadInt32();
					fs.Seek(cpos, SeekOrigin.Begin);

					// parameters for functions
					if(cmdType == 0) {
						i++;
						int paramCount = br.ReadInt32();
						sb.Append(' ').Append(paramCount.ToString("X8"));
						for(int j = 0; j < paramCount; j++) {
							i++;
							sb.Append(' ').Append(br.ReadInt32().ToString("X8"));
						}
					}
					byte[] data = Encoding.ASCII.GetBytes(sb.Append('\n').ToString());
					os.Write(data, 0, data.Length);
					os.Flush();
				}

				// index binay
				os = new FileStream(Path.ChangeExtension(targetPath, ".index.dat"), FileMode.Create);
				fs.Seek(indexoffset, SeekOrigin.Begin);
				Helpers.CopyStream(fs, os, indexcount * 16);

				// index ascii
				os = new FileStream(Path.ChangeExtension(targetPath, ".index.txt"), FileMode.Create);
				fs.Seek(indexoffset, SeekOrigin.Begin);
				for(int i = 0; i < indexcount; i++) {
					byte[] data = Encoding.ASCII.GetBytes(i.ToString("X8") + ": " + br.ReadInt32().ToString("X8") + " " + br.ReadInt32().ToString("X8") + " " + br.ReadInt32().ToString("X8") + " " + br.ReadInt32().ToString("X8") + "\n");
					os.Write(data, 0, data.Length);
				}

				// data binary
				os = new FileStream(Path.ChangeExtension(targetPath, ".data.dat"), FileMode.Create);
				for(int i = 0; i < datalength; i++) {
					os.WriteByte((byte)(fs.ReadByte() ^ 0xAA));
				}
			}
		}

19 View Source File : FileLineReaderTest.cs
License : Apache License 2.0
Project Creator : awslabs

[Fact]
        public void ResetReader()
        {
            const string testLine = nameof(testLine);
            var testFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            var reader = new FileLineReader();

            try
            {
                using (var readStream = new FileStream(testFile, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite))
                {
                    reader.ReadLine(readStream, _encoding);

                    // write a test line without new line to make the buffer contain data
                    File.AppendAllText(testFile, testLine);
                    replacedert.Null(reader.ReadLine(readStream, _encoding));

                    // reset
                    readStream.Seek(0, SeekOrigin.Begin);
                    reader.Reset();

                    // finish the line and replacedert
                    File.AppendAllText(testFile, Environment.NewLine);
                    replacedert.Equal(testLine, reader.ReadLine(readStream, _encoding));
                }
            }
            finally
            {
                File.Delete(testFile);
            }
        }

19 View Source File : frmAudioExtract.cs
License : MIT License
Project Creator : AyrA

private void btnScan_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(AudioDir))
            {
                try
                {
                    Directory.CreateDirectory(AudioDir);
                }
                catch (Exception ex)
                {
                    Log.Write("AudioExtract: Unable to create Audio directory");
                    Log.Write(ex);
                    MessageBox.Show($"Unable to create the output directory. Reason: {ex.Message}", "Can't create directory", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            FileStream FS;
            try
            {
                FS = File.OpenRead(tbResourceFile.Text);
            }
            catch (Exception ex)
            {
                Log.Write("AudioExtract: Unable to open pak file");
                Log.Write(ex);
                MessageBox.Show($"Unable to open the specified file. Reason: {ex.Message}", "Can't open file", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            //Disable controls
            btnScan.Enabled = false;
            btnSelectFile.Enabled = false;
            tbResourceFile.Enabled = false;

            Log.Write("AudioExtract: Begin audio extraction of {0}", tbResourceFile.Text);
            //Begin audio extraction
            WaveFinder.FindAudio(FS);
            pbFilePos.Maximum = 100;
            Thread T = new Thread(delegate ()
            {
                while (WaveFinder.IsScanning)
                {
                    Invoke((MethodInvoker)delegate
                    {
                        pbFilePos.Value = (int)(FS.Position * 100 / FS.Length);
                    });
                    Thread.Sleep(500);
                }
                Log.Write("AudioExtract: Audio extraction complete. Found {0} files", WaveFinder.WaveFiles.Length);
                using (FS)
                {
                    int Counter = 0;

                    //Order files descending but PCM first, then OGG
                    var FoundFiles = WaveFinder.WaveFiles
                    .Where(m => m.Type == WaveFileType.PCM)
                    .OrderByDescending(m => m.Header.DataSize)
                    .Concat(
                        WaveFinder.WaveFiles
                        .Where(m => m.Type == WaveFileType.OGG)
                        .OrderByDescending(m => m.Header.DataSize))
                    .ToArray();

                    Log.Write("AudioExtract: Exporting {0} files", FoundFiles.Length);

                    Invoke((MethodInvoker)delegate
                    {
                        pbFilePos.Value = 0;
                        pbFilePos.Maximum = FoundFiles.Length;
                    });

                    foreach (var F in FoundFiles)
                    {
                        var FileName = Path.Combine(AudioDir, string.Format("{0:0000}.{1}", ++Counter, F.Type == WaveFileType.PCM ? "wav" : "ogg"));
                        Invoke((MethodInvoker)delegate
                        {
                            pbFilePos.Value = Counter;
                        });
                        FileStream OUT;
                        try
                        {
                            OUT = File.Create(FileName);
                        }
                        catch (Exception ex)
                        {
                            Log.Write("AudioExtract: Unable to export {0}", FileName);
                            Log.Write(ex);
                            //Unable to create output file, skip
                            continue;
                        }
                        using (OUT)
                        {
                            FS.Seek(F.Header.DataOffset, SeekOrigin.Begin);
                            if (F.Type == WaveFileType.PCM)
                            {
                                //Fix values before writing new Header
                                //NOTE: Set different values here for different games
                                F.Header.AudioFormat = 1; //PCM
                                F.Header.BitsPerSample = 16;
                                F.Header.SampleRate = 44100;
                                //Fix computed values
                                F.Header.BlockAlign = (ushort)(F.Header.ChannelCount * F.Header.BitsPerSample / 8);
                                F.Header.ByteRate = F.Header.SampleRate * F.Header.ChannelCount * F.Header.BitsPerSample / 8;
                                F.Header.Write(OUT);
                            }
                            else
                            {
                                //OGG Doesn't needs the RIFF header, just write data
                            }
                            byte[] Data = new byte[F.Header.DataSize];
                            FS.Read(Data, 0, Data.Length);
                            OUT.Write(Data, 0, Data.Length);
                            Log.Write("AudioExtract: Exported {0} file", F.Type);
                        }
                    }
                }
                Invoke((MethodInvoker)delegate
                {
                    pbFilePos.Value = 0;
                    pbFilePos.Maximum = 100;
                    LoadAudioPlayer();
                    //Enable controls again
                    btnScan.Enabled = true;
                    btnSelectFile.Enabled = true;
                    tbResourceFile.Enabled = true;
                });
            });
            T.Start();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : AyrA

private static int HandleArguments(string[] args)
        {
            var Ops = new List<Modes>();
            string Filename = null;
            string SessionName = null;
            if (args.Contains("/?"))
            {
                Help();
                return RET.HELP;
            }
            for (var i = 0; i < args.Length; i++)
            {
                var arg = args[i];
                Log.Write("{0}: processing argument: {1}", nameof(HandleArguments), arg);
                switch (arg.ToLower())
                {
                    case "/verify":
                        Ops.Add(Modes.Verify);
                        break;
                    case "/list":
                        Ops.Add(Modes.List);
                        break;
                    case "/pack":
                        Ops.Add(Modes.Pack);
                        break;
                    case "/render":
                        Ops.Add(Modes.Render);
                        break;
                    case "/info":
                        Ops.Add(Modes.Info);
                        break;
                    case "/rename":
                        Ops.Add(Modes.RenameSession);
                        if (i < args.Length - 1)
                        {
                            SessionName = args[++i];
                        }
                        else
                        {
                            Log.Write("{0}: /rename requires a new session name", nameof(HandleArguments));
                            Console.WriteLine("/rename requires a new session name");
                            return RET.ARG;
                        }
                        break;
                    default:
                        if (string.IsNullOrEmpty(Filename))
                        {
                            Filename = arg;
                        }
                        else
                        {
                            Log.Write("{0}: unknown argument: {1}", nameof(HandleArguments), arg);
                            Console.WriteLine("Unknown argument: {0}", arg);
                            return RET.ARG;
                        }
                        break;
                }
            }

            if (Ops.Count == 0 && args.Length < 2)
            {
                return RET.UI;
            }

            Tools.AllocConsole();

            if (string.IsNullOrEmpty(Filename))
            {
                Log.Write("{0}: No file name argument supplied", nameof(HandleArguments));
                Console.WriteLine("No file name argument supplied");
                return RET.ARG;
            }

            Ops = Ops.Distinct().ToList();

            var Changes = false;
            var IsGz = false;
            SaveFile SF = null;
            FileStream FS = null;
            try
            {
                FS = File.Open(Filename, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to open input file");
                Log.Write("{0}: Unable to open input file", nameof(HandleArguments));
                Log.Write(ex);
                return RET.IO;
            }
            using (FS)
            {
                IsGz = Tools.IsGzFile(FS);
                try
                {
                    SF = SaveFile.Open(FS);
                    if (SF == null)
                    {
                        throw new InvalidDataException("The file is not a valid satisfactory save game");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Invalid game file");
                    Log.Write("{0}: Invalid game file", nameof(HandleArguments));
                    Log.Write(ex);
                    return RET.IO;
                }


                if (Ops.Contains(Modes.Verify))
                {
                    Log.Write("{0}: Verifying file", nameof(HandleArguments));
                    //Verify does nothing on its own
                    Check(SF.PlayTime.Ticks >= 0, "Positive play time");
                    Check(Tools.IsMatch(SF.SessionName, @"^[\w\.\- ]{1,31}$"), "Non-Problematic Session Name");
                    Check(SF.LevelType == SaveFile.DEFAULT_LEVEL_TYPE, $"Level type is '{SaveFile.DEFAULT_LEVEL_TYPE}'");
                    Check(SF.SaveDate.ToUniversalTime() < DateTime.UtcNow, "Date in past");
                    foreach (var key in "sessionName Visibility startloc".Split(' '))
                    {
                        Check(SF.Properties.ContainsKey(key), $"Header contains field '{key}'");
                    }
                    //Don't double error with the previous one
                    if (SF.Properties.ContainsKey("sessionName"))
                    {
                        Check(SF.Properties["sessionName"] == SF.SessionName, "Both session names match");
                    }
                    else
                    {
                        Console.WriteLine("[SKIP]: Both session names match");
                    }
                }

                if (Ops.Contains(Modes.List))
                {
                    Log.Write("{0}: Printing item list", nameof(HandleArguments));
                    foreach (var e in SF.Entries.GroupBy(m => m.ObjectData.Name).OrderBy(m => m.Key))
                    {
                        Console.WriteLine("{1}\t{0}", e.Key, e.Count());
                    }
                }

                if (Ops.Contains(Modes.Render))
                {
                    var ImgFile = Path.ChangeExtension(Filename, ".png");
                    Log.Write("{0}: Rendering map as original size to {1}", nameof(HandleArguments), ImgFile);
                    Console.WriteLine("Initializing image...");
                    MapRender.Init(-1, -1);
                    Console.WriteLine("Rendering file...");
                    using (var IMG = MapRender.RenderFile(SF, 8.192))
                    {
                        Console.WriteLine("Saving image...");
                        IMG.Save(ImgFile);
                    }
                }

                if (Ops.Contains(Modes.Info))
                {
                    Log.Write("{0}: Showing game info", nameof(HandleArguments));
                    Console.WriteLine("Save File Size:\t{0}", FS.Position);
                    Console.WriteLine("Build Version:\t{0}", SF.BuildVersion);
                    Console.WriteLine("Save Version:\t{0}", SF.SaveVersion);
                    Console.WriteLine("Header Version:\t{0}", SF.SaveHeaderVersion);
                    Console.WriteLine("Session Name:\t{0}", SF.SessionName);
                    Console.WriteLine("Save Date:\t{0}", SF.SaveDate);
                    Console.WriteLine("Play Time:\t{0}", SF.PlayTime);
                    foreach (var KV in SF.Properties)
                    {
                        Console.WriteLine("{0}:\t{1}", KV.Key, KV.Value);
                    }
                    Console.WriteLine("Object Count:\t{0}", SF.Entries.Count);
                    Console.WriteLine("String List:\t{0}", SF.StringList.Count);
                }

                if (Ops.Contains(Modes.RenameSession))
                {
                    Log.Write("{0}: Renaming session to {1}", nameof(HandleArguments), SessionName);
                    SF.SetSessionName(SessionName);
                    Changes = true;
                }

                if (Ops.Contains(Modes.Pack))
                {
                    string NewFile;
                    FileStream OUT;
                    FS.Seek(0, SeekOrigin.Begin);
                    if (IsGz)
                    {
                        if (Filename.ToLower().EndsWith(".sav.gz"))
                        {
                            NewFile = Path.ChangeExtension(Filename, null);
                        }
                        else
                        {
                            NewFile = Path.ChangeExtension(Filename, ".sav");
                        }
                    }
                    else
                    {
                        NewFile = Filename + ".gz";
                    }
                    try
                    {
                        OUT = File.Create(NewFile);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Can't create output file");
                        Log.Write("{0}: Can't create {1}", nameof(HandleArguments), NewFile);
                        Log.Write(ex);
                        return RET.IO;
                    }
                    Log.Write("{0}: {1} file", nameof(HandleArguments), IsGz ? "Compressing" : "Decompressing");
                    using (OUT)
                    {
                        if (IsGz)
                        {
                            Compression.DecompressStream(FS, OUT);
                        }
                        else
                        {
                            Compression.CompressStream(FS, OUT);
                        }
                    }
                    Log.Write("{0}: {1} file OK", nameof(HandleArguments), IsGz ? "Compressing" : "Decompressing");
                }
                if (Changes)
                {
                    Log.Write("{0}: Writing back changes", nameof(HandleArguments));
                    FS.Seek(0, SeekOrigin.Begin);
                    SF.Export(FS);
                    FS.Flush();
                    FS.SetLength(FS.Position);
                }
            }

            return RET.SUCCESS;
        }

19 View Source File : frmManager.cs
License : MIT License
Project Creator : AyrA

private void btnImport_Click(object sender, EventArgs e)
        {
            if (OFD.ShowDialog() == DialogResult.OK)
            {
                FileStream FS;
                try
                {
                    FS = File.OpenRead(OFD.FileName);
                }
                catch (Exception ex)
                {
                    Log.Write(new Exception($"Unable to import {OFD.FileName}", ex));
                    Tools.E($"Unable to open the selected file.\r\n{ex.Message}", "Import error");
                    return;
                }
                using (FS)
                {
                    var NewName = Path.GetFileName(OFD.FileName);
                    if (NewName.ToLower().Contains(".sav"))
                    {
                        //Make .sav the last part of the name
                        NewName = NewName.Substring(0, NewName.ToLower().LastIndexOf(".sav")) + ".sav";
                        if (NewName == ".sav")
                        {
                            NewName = "Import.sav";
                        }
                    }
                    else
                    {
                        //Add .sav extension because it's not there
                        NewName += ".sav";
                    }
                    //Make name unique
                    int i = 1;
                    while (File.Exists(Path.Combine(Program.SaveDirectory, NewName)))
                    {
                        NewName = NewName.Substring(0, NewName.Length - 4) + $"_{i++}.sav";
                    }

                    //Check if selected file is actually a (somewhat) valid save game
                    var F = SaveFile.Open(FS);
                    if (F == null)
                    {
                        NewName = Path.Combine(Program.SaveDirectory, NewName);
                        if (MessageBox.Show("This file doesn't looks like it's a save file. Import anyways?", "Incompatible file", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                        {
                            //User decided to copy anyway. Decompress the file now as needed
                            FS.Seek(0, SeekOrigin.Begin);
                            if (Tools.IsGzFile(FS))
                            {
                                Log.Write("{0}: looks compressed: {1}", GetType().Name, OFD.FileName);
                                try
                                {
                                    using (var GZS = new GZipStream(FS, CompressionMode.Decompress))
                                    {
                                        //Try to manually decompress a few bytes before fully copying.
                                        //This will throw an exception for files that are not decompressable before the output file is created
                                        byte[] Data = new byte[100];
                                        int R = GZS.Read(Data, 0, Data.Length);
                                        using (var OUT = File.Create(NewName))
                                        {
                                            OUT.Write(Data, 0, R);
                                            GZS.CopyTo(OUT);
                                        }
                                    }
                                    InitFiles();
                                    FeatureReport.Used(FeatureReport.Feature.RestoreBackup);
                                }
                                catch (Exception ex)
                                {
                                    Log.Write(new Exception($"Unable to decompress {OFD.FileName}", ex));
                                    Tools.E($"File looks compressed, but we are unable to decompress it.\r\n{ex.Message}", "Decompression error");
                                }
                            }
                            else
                            {
                                Log.Write("{0}: Importing uncompressed {1}", GetType().Name, OFD.FileName);
                                //File is not compressed. Just copy as-is
                                using (var OUT = File.Create(NewName))
                                {
                                    FS.CopyTo(OUT);
                                    InitFiles();
                                }
                            }
                        }
                    }
                    else
                    {
                        //Supply the NewName path to have a name that's not a conflict by default
                        using (var Ren = new frmRename(F.SessionName, Path.GetFileNameWithoutExtension(NewName)))
                        {
                            if (Ren.ShowDialog() == DialogResult.OK)
                            {
                                NewName = Path.Combine(Program.SaveDirectory, Ren.RenameFileName + ".sav");
                                if (!File.Exists(NewName) || MessageBox.Show($"There is already a file named {Ren.RenameFileName}.sav. Overwrite this file?", "Confirm overwrite", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                                {
                                    F.SessionName = Ren.RenameSessionName;
                                    using (var OUT = File.Create(NewName))
                                    {
                                        F.Export(OUT);
                                    }
                                    InitFiles();
                                }
                                else
                                {
                                    Log.Write("{0}: import destination exists: User cancelled", GetType().Name);
                                }
                            }
                        }
                    }
                }
            }
        }

19 View Source File : LocalFileSystemStream.cs
License : MIT License
Project Creator : azist

protected override long DoSeek(long offset, SeekOrigin origin)
    {
      return m_FS.Seek(offset, origin);
    }

19 View Source File : LocalFileSystem.cs
License : MIT License
Project Creator : azist

protected internal override FileSystemFile DoCreateFile(FileSystemDirectory dir, string name, int size)
      {
        var fn = Path.Combine(dir.Path, name);
        using(var fs = new FileStream(fn, FileMode.Create, FileAccess.Write))
        {
          if (size>0)
          {
           fs.Seek(size-1, SeekOrigin.Begin);
           fs.WriteByte(0);
          }
        }

        var fi = new FileInfo(fn);
        return new FileSystemFile(dir.Session, fi.DirectoryName, fi.Name, new FSH{m_Info = fi});
      }

See More Examples