System.IO.FileStream.Write(byte[], int, int)

Here are the examples of the csharp api System.IO.FileStream.Write(byte[], int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1268 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 : LogFileWriter.cs
License : MIT License
Project Creator : 0ffffffffh

public void Write(byte[] buffer, int writeLen)
        {
            lock (lck)
            {
                if (logFile == null)
                    return;

                if (logFile.Position > 2 * 1024 * 1024)
                {
                    logFile.Flush();
                    logFile.Dispose();

                    logFile = new FileStream(
                        Log.GetLogFileName(compType), 
                        FileMode.Append, 
                        FileAccess.Write, 
                        FileShare.Read
                        );
                }

                logFile.Write(buffer, 0, writeLen);
                logFile.Write(lineFeed, 0, lineFeed.Length);

                if (!needsFlush)
                    needsFlush = true;
                
            }
        }

19 View Source File : RawFileType.cs
License : MIT License
Project Creator : 0xC0000054

protected override Doreplacedent OnLoad(Stream input)
        {
            Doreplacedent doc = null;
            string tempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            try
            {
                // Write the input stream to a temporary file for LibRaw to load.
                using (FileStream output = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    if (input.CanSeek)
                    {
                        output.SetLength(input.Length);
                    }

                    // 81920 is the largest multiple of 4096 that is under the large object heap limit (85,000 bytes).
                    byte[] buffer = new byte[81920];

                    int bytesRead;
                    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        output.Write(buffer, 0, bytesRead);
                    }
                }

                doc = GetRAWImageDoreplacedent(tempFile);
            }
            finally
            {
                File.Delete(tempFile);
            }

            return doc;
        }

19 View Source File : ImageLoading.cs
License : GNU General Public License v3.0
Project Creator : 1330-Studios

public static void SaveToPNG(Sprite s, String name) {
            byte[] b = ImageConversion.EncodeToPNG(s.texture);
            byte[] bytes = new byte[b.Length];

            for (int i = 0; i < b.Length; i++) {
                bytes[i] = b[i];
            }

            File.Create(name).Write(bytes, 0, bytes.Length);
        }

19 View Source File : TemplateGenerator.cs
License : MIT License
Project Creator : 2881099

void BuildEachDirectory(string templateDirectory, string outputDirectory, TemplateEngin tpl, IDbFirst dbfirst, List<DbTableInfo> tables) {
			if (Directory.Exists(outputDirectory) == false) Directory.CreateDirectory(outputDirectory);
			var files = Directory.GetFiles(templateDirectory);
			foreach (var file in files) {
				var fi = new FileInfo(file);
				if (string.Compare(fi.Extension, ".FreeSql", true) == 0) {
					var outputExtension = "." + fi.Name.Split('.')[1];
					if (fi.Name.StartsWith("for-table.")) {
						foreach (var table in tables) {
							var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "table", table }, { "dbfirst", dbfirst } });
							if (result.EndsWith("return;")) continue;
							var outputName = table.Name + outputExtension;
							var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
							if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
							var outputStream = Encoding.UTF8.GetBytes(result);
							var fullname = outputDirectory + "/" + outputName;
							if (File.Exists(fullname)) File.Delete(fullname);
							using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
								outfs.Write(outputStream, 0, outputStream.Length);
								outfs.Close();
							}
						}
						continue;
					} else {
						var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "tables", tables }, { "dbfirst", dbfirst } });
						var outputName = fi.Name;
						var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
						if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
						var outputStream = Encoding.UTF8.GetBytes(result);
						var fullname = outputDirectory + "/" + outputName;
						if (File.Exists(fullname)) File.Delete(fullname);
						using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
							outfs.Write(outputStream, 0, outputStream.Length);
							outfs.Close();
						}
					}
				}
				File.Copy(file, outputDirectory + file.Replace(templateDirectory, ""), true);
			}
			var dirs = Directory.GetDirectories(templateDirectory);
			foreach(var dir in dirs) {
				BuildEachDirectory(dir, outputDirectory +  dir.Replace(templateDirectory, ""), tpl, dbfirst, tables);
			}
		}

19 View Source File : FileManager.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static bool ByteArrayToFile(string fileName, byte[] content)
        {
            try
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                    fs.Write(content, 0, content.Length);
                return true;
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
            }
            return false;
        }

19 View Source File : FileManager.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static void UncompressFile(string fileName, byte[] content)
        {
            try
            {
                // Because the uncompressed size of the file is unknown,
                // we are using an arbitrary buffer size.
                byte[] buffer = new byte[4096];
                int n;

                using (FileStream fs = File.Create(fileName))
                using (GZipStream input = new GZipStream(new MemoryStream(content),
                        CompressionMode.Decompress, false))
                {
                    while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fs.Write(buffer, 0, n);
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
            }
        }

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

public static void Savereplacedet(string path, byte[] bytes)
        {
            using (FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                fileStream.Write(bytes, 0, bytes.Length);
            }
        }

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

public void StartDownload()
                {
                    try
                    {
                        HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(m_HttpDownloadInfo.Url);

                        if (0L < m_Position)
                        {
                            httpWebRequest.AddRange((int)m_Position);
                        }

                        WebResponse webResponse = httpWebRequest.GetResponse();
                        Stream webResponseStream = webResponse.GetResponseStream();

                        float progress = 0f;
                        long currentSize = m_Position;
                        long totalSize = m_Position + webResponse.ContentLength;

                        byte[] btContent = new byte[m_HttpDownloadInfo.DownloadBufferUnit];
                        int readSize = 0;
                        while (!m_Hreplacedtop && 0 < (readSize = webResponseStream.Read(btContent, 0, m_HttpDownloadInfo.DownloadBufferUnit)))
                        {
                            progress = (float)(currentSize += readSize) / totalSize;
                            if (null != OnDownloadProgress)
                            {
                                OnDownloadProgress.Invoke(this, new HttpDownloaderProgressEventArgs(progress));
                            }
                            m_FileStream.Flush();
                            m_FileStream.Write(btContent, 0, readSize);

                            System.Threading.Thread.Sleep(10);

                        }
                        m_FileStream.Close();
                        webResponseStream.Close();

                        if (!m_Hreplacedtop)
                        {
                            ReNameTempFile();

                            if (null != OnDownloadSuccess)
                            {
                                OnDownloadSuccess.Invoke(this, EventArgs.Empty);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (null != OnDownloadFailure)
                        {
                            OnDownloadFailure.Invoke(this,new HttpDownloaderFailureEventArgs(ex));
                        }
                        throw ex;
                    }
                }

19 View Source File : FileChecker.cs
License : Apache License 2.0
Project Creator : AantCoder

public static void FileSynchronization(string modsDir, ModelModsFiles serverFiles)
        {
            restoreFolderTree(modsDir, serverFiles.FoldersTree);

            foreach (var serverFile in serverFiles.Files)
            {
                var fullName = Path.Combine(modsDir, serverFile.FileName);
                // Имя присутствует в списке, файл необходимо будет удалить ( или заменить)
                if (File.Exists(fullName))
                {
                    File.Delete(fullName);
                }

                if (serverFile.Hash == null)
                {
                    continue;
                }


                // Create the file, or overwrite if the file must exist.
                using (FileStream fs = File.Create(fullName))
                {
                    Loger.Log("Restore: " + fullName);

                    if (serverFile.Hash.Length > 0)
                    {
                        fs.Write(serverFile.Hash, 0, serverFile.Hash.Length);
                    }
                }
            }
        }

19 View Source File : MetadataAnalyzer.cs
License : MIT License
Project Creator : aerosoul94

private void DumpFile(DirectoryEntry dirent, string path)
        {
            path = path + "/" + dirent.FileName;
            const int bufsize = 0x100000;
            var remains = dirent.FileSize;
            _volume.SeekToCluster(dirent.FirstCluster);

            using (FileStream file = new FileStream(path, FileMode.Create))
            {
                while (remains > 0)
                {
                    var read = Math.Min(remains, bufsize);
                    remains -= read;
                    byte[] buf = new byte[read];
                    _volume.GetReader().Read(buf, (int)read);
                    file.Write(buf, 0, (int)read);
                }
            }

            File.SetCreationTime(path, dirent.CreationTime.AsDateTime());
            File.SetLastWriteTime(path, dirent.LastWriteTime.AsDateTime());
            File.SetLastAccessTime(path, dirent.LastAccessTime.AsDateTime());
        }

19 View Source File : CarverResults.cs
License : MIT License
Project Creator : aerosoul94

private void SaveFile(FileSignature signature, string path)
        {
            const int bufsize = 0x100000;
            var remains = signature.FileSize;
            _volume.SeekFileArea(signature.Offset);

            path = path + "/" + signature.FileName;
            var uniquePath = Utility.UniqueFileName(path);
            using (FileStream file = new FileStream(uniquePath, FileMode.Create))
            {
                while (remains > 0)
                {
                    var read = Math.Min(remains, bufsize);
                    remains -= read;
                    byte[] buf = new byte[read];
                    _volume.GetReader().Read(buf, (int)read);
                    file.Write(buf, 0, (int)read);
                }
            }
        }

19 View Source File : FileExplorer.cs
License : MIT License
Project Creator : aerosoul94

private void WriteFile(string path, DirectoryEntry dirent, List<uint> chainMap)
            {
                using (FileStream outFile = File.OpenWrite(path))
                {
                    uint bytesLeft = dirent.FileSize;

                    foreach (uint cluster in chainMap)
                    {
                        byte[] clusterData = this.volume.ReadCluster(cluster);

                        var writeSize = Math.Min(bytesLeft, this.volume.BytesPerCluster);
                        outFile.Write(clusterData, 0, (int)writeSize);

                        bytesLeft -= writeSize;
                    }
                }
            }

19 View Source File : RecoveryResults.cs
License : MIT License
Project Creator : aerosoul94

private void WriteFile(string path, DatabaseFile databaseFile)
            {
                using (FileStream outFile = File.OpenWrite(path))
                {
                    uint bytesLeft = databaseFile.FileSize;

                    foreach (uint cluster in databaseFile.ClusterChain)
                    {
                        byte[] clusterData = this.volume.ReadCluster(cluster);

                        var writeSize = Math.Min(bytesLeft, this.volume.BytesPerCluster);
                        outFile.Write(clusterData, 0, (int)writeSize);

                        bytesLeft -= writeSize;
                    }
                }
            }

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

protected override void DoOperation()
	{
		stageReached = Savereplacedtage.BeforeCreate;

		if (!CheckFreeSpace(Path.GetDirectoryName(savePath), 0)) {
			string msg = string.Format(Catalog.GetString("There is not enough free space on the device to save file '{0}'."), savePath);
			throw new IOException(msg);
		}

		// try to open in append mode first, so that a sharing violation
		// doesn't end up with the file truncated (as opposed
		// to using FileMode.Create)
		fs = new FileStream(savePath, FileMode.Append, FileAccess.Write);
		fs.Close();
		
		// do the actual create
		fs = new FileStream(savePath, FileMode.Create, FileAccess.Write);
		
		stageReached = Savereplacedtage.BeforeWrite;
		
		const int blockSize = 0xffff;
		
		byte[] baTemp = new byte[blockSize];
		
		// for every node
		Util.List<Segment>.Node node = byteBuffer.segCol.List.First;
		
		while (node != null && !cancelled)
		{
			// Save the data in the node 
			// in blocks of blockSize each
			Segment s = node.data;
			long len = s.Size;
			long nBlocks = len/blockSize;
			int last = (int)(len % blockSize); // bytes in last block
			long i;
		
			// 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);
			}
					
			node = node.next;
		}	
		
		fs.Close();
		fs = null;	
	}

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 : IconFile.cs
License : MIT License
Project Creator : ahopper

static public void SaveToICO(Drawing drawing, List<int> sizes, string filename)
        {
            int headerLen = 6 + sizes.Count * 16;
            using (var icoStream = new MemoryStream())
            {
                //write ICONDIR
                icoStream.WriteByte(0);
                icoStream.WriteByte(0);
                icoStream.WriteByte(1);
                icoStream.WriteByte(0);
                icoStream.WriteByte((byte)sizes.Count);
                icoStream.WriteByte(0);
                
                icoStream.Position = headerLen;
                
                for (int i =0; i< sizes.Count; i++)
                {
                    var start = icoStream.Position;
                    SaveDrawing(drawing, sizes[i], icoStream);
                    var end = icoStream.Position;
                    int pngLen = (int)(end - start);
               
                    icoStream.Position = 6 + i * 16;
                    icoStream.WriteByte((byte)sizes[i]);
                    icoStream.WriteByte((byte)sizes[i]);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(32);

                    icoStream.WriteByte((byte)(pngLen & 0xff));
                    icoStream.WriteByte((byte)((pngLen >> 8) & 0xff)); 
                    icoStream.WriteByte((byte)((pngLen >> 16) & 0xff));
                    icoStream.WriteByte((byte)(pngLen >> 24));
                   
                    icoStream.WriteByte((byte)(start & 0xff)); 
                    icoStream.WriteByte((byte)((start >> 8) & 0xff));
                    icoStream.WriteByte((byte)((start >> 16) & 0xff));
                    icoStream.WriteByte((byte)(start >> 24));
           
                    icoStream.Position=end;
                }
                using(var icoFile=File.Create(filename))
                {
                    icoFile.Write(icoStream.GetBuffer(), 0, (int)icoStream.Position);
                }
            }
        }

19 View Source File : IconFile.cs
License : MIT License
Project Creator : ahopper

static public void SaveToICNS(Drawing drawing, List<int> sizes, string filename)
        {
            int headerLen = 8;
            int fileLen = headerLen;
            using (var icoStream = new MemoryStream())
            {
                icoStream.WriteByte(0x69);
                icoStream.WriteByte(0x63);
                icoStream.WriteByte(0x6e);
                icoStream.WriteByte(0x73);
                
                icoStream.Position = headerLen;

                for (int i = 0; i < sizes.Count; i++)
                {
                    var start = icoStream.Position;
                    icoStream.Position += 8;
                    SaveDrawing(drawing, sizes[i], icoStream);
                    var end = icoStream.Position;
                    int pngLen = (int)(end - start);
                    fileLen += pngLen;

                    icoStream.Position = start;
                    string iconType;
                    switch(sizes[i])
                    {
                        case 16: iconType = "icp4"; break;
                        case 32: iconType = "icp5"; break;
                        case 64: iconType = "icp6"; break;
                        case 128: iconType = "ic07"; break;
                        case 256: iconType = "ic08"; break;
                        case 512: iconType = "ic09"; break;
                        default: throw new Exception($"Unsupported icns size {sizes[i]}");
                    }
                    icoStream.Write(ASCIIEncoding.ASCII.GetBytes(iconType));

                    icoStream.WriteByte((byte)(pngLen >> 24));
                    icoStream.WriteByte((byte)((pngLen >> 16) & 0xff));
                    icoStream.WriteByte((byte)((pngLen >> 8) & 0xff));
                    icoStream.WriteByte((byte)(pngLen & 0xff));
                    
                    icoStream.Position = end;
                }
                icoStream.Position = 4;

                icoStream.WriteByte((byte)(fileLen >> 24));
                icoStream.WriteByte((byte)((fileLen >> 16) & 0xff));
                icoStream.WriteByte((byte)((fileLen >> 8) & 0xff));
                icoStream.WriteByte((byte)(fileLen & 0xff));
                
                using (var icoFile = File.Create(filename))
                {
                    icoFile.Write(icoStream.GetBuffer(), 0, fileLen);
                }
            }
        }

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

private long WriteImageData(Snapshot sshot, Database db)
		{
			long position;
			try
			{
				var sessionDate = db.SelectSingle<DateTime>("SessionInfo", "CreateTime", new { SessionId = sshot.SessionId });
				string path = Path.Combine(DataPath, string.Format(@"{0:yyyy}\{0:MMdd}\{1}.rdt", sessionDate, sshot.SessionId));
				if (!Directory.Exists(Path.GetDirectoryName(path)))
					Directory.CreateDirectory(Path.GetDirectoryName(path));
				using (FileStream fs = File.Open(path, FileMode.Append, FileAccess.Write, FileShare.Read))
				{
					position = fs.Position;
					if (sshot.ImageData != null && sshot.ImageData.Length > 0)
					{
						fs.Write(sshot.ImageData, 0, sshot.ImageData.Length);
					}
					Debug.replacedert(sshot.EventsData != null && sshot.EventsData.Length > 0 && sshot.EventsData.Length % 16 == 0);
					fs.Write(sshot.EventsData, 0, sshot.EventsData.Length);
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return position;
		}

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

private void WriteImageData(Snapshot sshot, out long imgPos, out int imgLen)
		{
			try
			{
				switch ((ImageStorageType)Global.Config.ImageStorage)
				{
					case ImageStorageType.TextOnly:
						imgPos = imgLen = 0;
						break;
					case ImageStorageType.GrayScale:
						break;
					case ImageStorageType.RawImage:
						break;
				}
				
				string path = Path.Combine(DataPath, sshot.SessionId + ".rdt");
				using (FileStream fs = File.Open(path, FileMode.Append, FileAccess.Write, FileShare.Read))
				{
					if (sshot.ImageData != null && sshot.ImageData.Length > 0)
					{
						imgPos = fs.Position;
						fs.Write(sshot.ImageData, 0, sshot.ImageData.Length);
						fs.Write(sshot.EventsData, 0, sshot.EventsData.Length);
						imgLen = sshot.ImageData.Length;
					}
					else
					{
						imgPos = fs.Position;
						fs.Write(sshot.EventsData, 0, sshot.EventsData.Length);
						imgLen = 0;
					}
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
		}

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

public void WriteSnapshot(Snapshot sshot)
		{
			try
			{
				Debug.replacedert(sshot.EventsData.Length > 0 && sshot.EventsData.Length % 16 == 0);
				if (!string.IsNullOrEmpty(sshot.WindowUrl) && sshot.Url == null)
					TraceLogger.Instance.WriteLineInfo("Url can not be parsed: " + sshot.WindowUrl);

				long imgPos, imgLen;
				string path = Path.Combine(DataPath, sshot.SessionId + ".rdt");
				using (FileStream fs = File.Open(path, FileMode.Append, FileAccess.Write, FileShare.Read))
				{
					if (sshot.ImageData != null && sshot.ImageData.Length > 0)
					{
						imgPos = fs.Position;
						fs.Write(sshot.ImageData, 0, sshot.ImageData.Length);
						fs.Write(sshot.EventsData, 0, sshot.EventsData.Length);
						imgLen = sshot.ImageData.Length;
					}
					else
					{
						imgPos = fs.Position;
						fs.Write(sshot.EventsData, 0, sshot.EventsData.Length);
						imgLen = 0;
					}
				}

				using (Database db = new Database())
				{
					var ss = new
					{
						SessionId = sshot.SessionId,
						SnapshotId = sshot.SnapshotId,
						SnapTime = sshot.SnapTime,
						ProcessId = sshot.ProcessId,
						ProcessName = sshot.ProcessName,
						WindowHandle = sshot.WindowHandle,
						WindowRect = DataConverter.Serialize(sshot.WindowRect),

						Windowreplacedle = sshot.Windowreplacedle,
						WindowUrl = sshot.Url == null ? sshot.WindowUrl : sshot.Url.AbsoluteUri,
						UrlHost = sshot.Url == null ? null : sshot.Url.Host,

						//MouseState = DataConverter.Serialize(sshot.Mouse),
						ImagePos = imgPos,
						ImageLength = imgLen,
						IsGrayScale = sshot.IsGrayScale,

						ControlText = sshot.ControlText,
						InputText = sshot.InputText,
						EventsCount = sshot.EventsCount,
					};

					db.InsertDistinct("Snapshots", ss, new { SnapshotId = sshot.SnapshotId });
					if (!string.IsNullOrEmpty(sshot.ProcessName))
						db.InsertDistinct("ApplicationInfo", new { ProcessName = ss.ProcessName });
					if (!string.IsNullOrEmpty(ss.UrlHost))
					{
						string name = ss.UrlHost.StartsWith("www.") ? ss.UrlHost.Substring(4) : ss.UrlHost;
						name = name.EndsWith(".com") ? name.Substring(0, name.Length - 4) : name;
						db.InsertDistinct("HostInfo", new { HostUrl = ss.UrlHost, HostName = name }, new { HostUrl = ss.UrlHost });
					}
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
		}

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

public long WriteImageData(string sessionId, byte[] imgData, byte[] addData)
		{
			Debug.replacedert(sessionId != null && imgData != null && imgData.Length > 0);
			long pos;
			try
			{
				string path = Path.Combine(DataPath, sessionId + ".rdm");
				using (FileStream fs = File.Open(path, FileMode.Append, FileAccess.Write, FileShare.Read))
				{
					pos = fs.Position;
					fs.Write(imgData, 0, imgData.Length);
					fs.Write(addData, 0, addData.Length);
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return pos;
		}

19 View Source File : Modules.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : airzero24

public static bool Upload(string File, string ChunkData)
        {
            try
            {
                byte[] chunk_data = Convert.FromBase64String(ChunkData);
                using (FileStream fileStream = new FileStream(File, FileMode.Append))
                {
                    fileStream.Write(chunk_data, 0, chunk_data.Length);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : akalankauk

public bool EncryptFile(string inputFile)
        {
            string name = GetFileName(inputFile);
            string ext = GetFileExt(inputFile);
            byte[] bext = StrToByteArray(ext, new UnicodeEncoding());
            int k = bext.Length;
            try
            {
                FileStream fsRead = new FileStream(inputFile, FileMode.Open);
                FileStream fsWrite = new FileStream(name + ".ae", FileMode.Create);
                fsWrite.Write(BitConverter.GetBytes(k), 0, 4);
                fsWrite.Write(bext, 0, k);
                int data;
                while ((data = fsRead.ReadByte()) != -1) fsWrite.WriteByte(ByteEncrypt((byte)data));
                fsRead.Close();
                fsWrite.Close();
                File.Delete(inputFile);
                return true;
            }
            catch { }
            return false;
        }

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

public static void AppendDataBytesToFile(string filePath, byte[] dataBytes)
        {
            using (var fs = File.Open(filePath, FileMode.Append, FileAccess.Write, FileShare.None))
            {
                fs.Write(dataBytes, 0, dataBytes.Length);
            }
        }

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

private async Task SaveAction()
        {
            var extension = FileAttachment.GroupMeDoreplacedentMimeTypeMapper.MimeTypeToExtension(this.FileData.MimeType);

            var fileDialogService = Ioc.Default.GetService<IFileDialogService>();
            var filters = new List<FileFilter>
            {
                new FileFilter() { Name = "Doreplacedent", Extensions = { extension } },
            };

            var filename = fileDialogService.ShowSaveFileDialog("Save Doreplacedent", filters, this.FileData.FileName);
            if (!string.IsNullOrEmpty(filename))
            {
                this.IsLoading = true;
                var data = await this.FileAttachment.DownloadFileAsync(this.Message);

                using (var fs = File.OpenWrite(filename))
                {
                    fs.Write(data, 0, data.Length);
                }

                this.IsLoading = false;
            }
        }

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

private async Task SaveAction()
        {
            var extension = FileAttachment.GroupMeDoreplacedentMimeTypeMapper.MimeTypeToExtension(this.FileData.MimeType);

            var saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialFileName = this.FileData.FileName;
            saveFileDialog.Filters.Add(new FileDialogFilter() { Name = "Doreplacedent", Extensions = { extension } });

            var fileName = await saveFileDialog.ShowAsync(Program.GroupMeMainWindow);

            if (!string.IsNullOrEmpty(fileName))
            {
                this.IsLoading = true;
                var data = await this.FileAttachment.DownloadFileAsync(this.MessageContainer.Messages.First());

                using (var fs = File.OpenWrite(fileName))
                {
                    fs.Write(data, 0, data.Length);
                }

                this.IsLoading = false;
            }
        }

19 View Source File : PersistentSettings.cs
License : MIT License
Project Creator : AlexGyver

public void Save(string fileName) {

      XmlDoreplacedent doc = new XmlDoreplacedent();
      doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null));
      XmlElement configuration = doc.CreateElement("configuration");
      doc.AppendChild(configuration);
      XmlElement appSettings = doc.CreateElement("appSettings");
      configuration.AppendChild(appSettings);
      foreach (KeyValuePair<string, string> keyValuePair in settings) {
        XmlElement add = doc.CreateElement("add");
        add.SetAttribute("key", keyValuePair.Key);
        add.SetAttribute("value", keyValuePair.Value);
        appSettings.AppendChild(add);
      }

      byte[] file;
      using (var memory = new MemoryStream()) {
        using (var writer = new StreamWriter(memory, Encoding.UTF8)) {
          doc.Save(writer);
        }
        file = memory.ToArray();
      }

      string backupFileName = fileName + ".backup";
      if (File.Exists(fileName)) {
        try {
          File.Delete(backupFileName);
        } catch { }
        try {
          File.Move(fileName, backupFileName);
        } catch { }
      }

      using (var stream = new FileStream(fileName, 
        FileMode.Create, FileAccess.Write))
      {
        stream.Write(file, 0, file.Length);
      }

      try {
        File.Delete(backupFileName);
      } catch { }
    }

19 View Source File : Ring0.cs
License : MIT License
Project Creator : AlexGyver

private static bool ExtractDriver(string fileName) {
      string resourceName = "OpenHardwareMonitor.Hardware." +
        (OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" : 
        "WinRing0.sys");

      string[] names = Getreplacedembly().GetManifestResourceNames();
      byte[] buffer = null;
      for (int i = 0; i < names.Length; i++) {
        if (names[i].Replace('\\', '.') == resourceName) {
          using (Stream stream = Getreplacedembly().
            GetManifestResourceStream(names[i])) 
          {
              buffer = new byte[stream.Length];
              stream.Read(buffer, 0, buffer.Length);
          }
        }
      }

      if (buffer == null)
        return false;

      try {
        using (FileStream target = new FileStream(fileName, FileMode.Create)) {
          target.Write(buffer, 0, buffer.Length);
          target.Flush();
        }
      } catch (IOException) { 
        // for example there is not enough space on the disk
        return false; 
      }

      // make sure the file is actually writen to the file system
      for (int i = 0; i < 20; i++) {
        try {
          if (File.Exists(fileName) &&
            new FileInfo(fileName).Length == buffer.Length) 
          {
            return true;
          }
          Thread.Sleep(100);
        } catch (IOException) {
          Thread.Sleep(10);
        }
      }
      
      // file still has not the right size, something is wrong
      return false;
    }

19 View Source File : PersistenceManager.cs
License : MIT License
Project Creator : aljazsim

private void Write(FileStream stream, long offset, int length, byte[] buffer, int bufferOffset = 0)
        {
            stream.CannotBeNull();
            offset.MustBeGreaterThanOrEqualTo(0);
            buffer.CannotBeNullOrEmpty();
            length.MustBeGreaterThan(0);
            length.MustBeLessThanOrEqualTo(buffer.Length);
            bufferOffset.MustBeGreaterThanOrEqualTo(0);
            bufferOffset.MustBeLessThanOrEqualTo((int)(buffer.Length - length));

            if (stream.Length >= offset + length)
            {
                stream.Position = offset;
                stream.Write(buffer, bufferOffset, length);
            }
            else
            {
                throw new TorrentPersistanceException("Incorrect file length.");
            }
        }

19 View Source File : FifoServer.cs
License : Apache License 2.0
Project Creator : allenai

public void SendEOM() {
            serverPipe.Write(this.eomHeader, 0, this.headerLength);
            serverPipe.Flush();
        }

19 View Source File : FifoServer.cs
License : Apache License 2.0
Project Creator : allenai

public void SendMessage(FieldType t, byte[] body) {
            if (this.serverPipe == null) {
                this.serverPipe = new FileStream(this.serverPipePath, FileMode.Open, FileAccess.Write);
            }
            // Console.WriteLine("server pipe + connected " + this.serverPipe.IsConnected );
            byte[] header = new byte[headerLength];
            header[0] = (byte)t;
            PackNetworkBytes(body.Length).CopyTo(header, 1);
            serverPipe.Write(header, 0, header.Length);
            serverPipe.Write(body, 0, body.Length);
        }

19 View Source File : JsonFileIO.cs
License : MIT License
Project Creator : ambleside138

public static void Serialize<T>(T source, string filePath)
        {
            const int RetryMaxCount = 3;
            var tryCount = 0;

            while(true)
            {
                tryCount++;

                try
                {
                    using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                    {
                        var jsonString = JsonSerializer.SerializeToUtf8Bytes(source, _Options);
                        stream.Write(jsonString);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    if(tryCount < RetryMaxCount)
                    {
                        _Logger.Warn(ex, "ファイルの出力に失敗しました。1秒後にリトライします path=" + filePath);
                        Task.Delay(1000);
                    }
                    else
                    {
                        _Logger.Error(ex, "リトライ回数の上限に達したため処理を中止します");
                        break;
                    }
                }
            }

        }

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 : Interface.cs
License : MIT License
Project Creator : Aminator

public static void Unpack(string inputFilePath, string outputDirectoryPath)
        {
            if (!File.Exists(inputFilePath))
                throw new ArgumentException("Input file does not exists");
            if (!Directory.Exists(outputDirectoryPath))
                throw new ArgumentException("Ouput directory does not exists");

            string inputFileName = Path.GetFileNameWithoutExtension(inputFilePath);
            string inputDirectoryPath = Path.GetDirectoryName(inputFilePath);

            var model = LoadModelAsync(inputFilePath).Result;
            GltfLoader.Schema.Buffer binBuffer = null;
            byte[] binBufferData = null;
            if (model.Buffers != null && string.IsNullOrEmpty(model.Buffers[0].Uri))
            {
                binBuffer = model.Buffers[0];
                binBufferData = model.LoadBinaryBuffer(0, inputFilePath);
            }

            var imageBufferViewIndices = new List<int>();

            if (model.Images != null)
            {
                for (var index = 0; index < model.Images.Length; index++)
                {
                    var image = model.Images[index];

                    if (!string.IsNullOrEmpty(image.Uri))
                    {
                        if (!image.Uri.StartsWith("data:"))
                        {
                            var sourceFilePath = Path.Combine(inputDirectoryPath, image.Uri);
                            var fileName = $"{inputFilePath}_image{index}.bin";

                            if (File.Exists(sourceFilePath))
                            {
                                var destinationFilePath = Path.Combine(outputDirectoryPath, fileName);
                                File.Copy(sourceFilePath, destinationFilePath, true);
                            }

                            image.Uri = fileName;
                        }
                    }
                    else if (image.BufferView.HasValue)
                    {
                        var bufferView = model.BufferViews[image.BufferView.Value];
                        if (bufferView.Buffer == 0)
                        {
                            imageBufferViewIndices.Add(image.BufferView.Value);

                            var fileExtension = image.MimeType == "image/jpeg" ? "jpg" : "png";
                            var fileName = $"{inputFileName}_image{index}.{fileExtension}";

                            using (var fileStream = File.Create(Path.Combine(outputDirectoryPath, fileName)))
                            {
                                fileStream.Write(binBufferData, bufferView.ByteOffset, bufferView.ByteLength);
                            }

                            image.BufferView = null;
                            image.MimeType = null;
                            image.Uri = fileName;
                        }
                    }
                }
            }

            if (model.BufferViews != null)
            {
                var binFileName = $"{inputFileName}.bin";
                var binFilePath = Path.Combine(outputDirectoryPath, binFileName);
                var binByteLength = 0;

                var indexMap = new Dictionary<int, int>();
                var bufferViews = new List<BufferView>();
                using (var fileStream = File.Create(binFilePath))
                {
                    for (var index = 0; index < model.BufferViews.Length; index++)
                    {
                        if (!imageBufferViewIndices.Any(imageIndex => imageIndex == index))
                        {
                            var bufferView = model.BufferViews[index];
                            if (bufferView.Buffer == 0)
                            {
                                fileStream.Align(4);
                                var fileStreamPosition = fileStream.Position;
                                fileStream.Write(binBufferData, bufferView.ByteOffset, bufferView.ByteLength);
                                bufferView.ByteOffset = (int)fileStreamPosition;
                            }

                            var newIndex = bufferViews.Count;
                            if (index != newIndex)
                            {
                                indexMap.Add(index, newIndex);
                            }

                            bufferViews.Add(bufferView);
                        }
                    }

                    binByteLength = (int)fileStream.Length;
                }

                model.BufferViews = bufferViews.ToArray();

                if (binByteLength == 0)
                {
                    File.Delete(binFilePath);
                    if (binBuffer != null)
                    {
                        model.Buffers = model.Buffers.Skip(1).ToArray();
                        foreach (var bufferView in model.BufferViews)
                        {
                            bufferView.Buffer--;
                        }
                    }
                }
                else
                {
                    binBuffer.Uri = binFileName;
                    binBuffer.ByteLength = binByteLength;
                }

                if (model.Accessors != null)
                {
                    foreach (var accessor in model.Accessors)
                    {
                        if (accessor.BufferView.HasValue)
                        {
                            if (indexMap.TryGetValue(accessor.BufferView.Value, out int newIndex))
                            {
                                accessor.BufferView = newIndex;
                            }
                        }
                    }
                }
            }

            if (model.Buffers != null)
            {
                for (var index = 1; index < model.Buffers.Length; index++)
                {
                    var buffer = model.Buffers[index];
                    if (!buffer.Uri.StartsWith("data:"))
                    {
                        var sourceFilePath = Path.Combine(inputDirectoryPath, buffer.Uri);
                        var fileName = $"{inputFileName}{index}.bin";

                        if (File.Exists(sourceFilePath))
                        {
                            var destinationFilePath = Path.Combine(outputDirectoryPath, fileName);
                            File.Copy(sourceFilePath, destinationFilePath, true);
                        }

                        buffer.Uri = fileName;
                    }
                }
            }

            SaveModel(model, Path.Combine(outputDirectoryPath, $"{inputFileName}.gltf"));
        }

19 View Source File : AntiTamper.cs
License : MIT License
Project Creator : AnErrupTion

public static void Inject(string filePath)
        {
            using (MD5 hash = MD5.Create())
            {
                byte[] bytes = hash.ComputeHash(File.ReadAllBytes(filePath));

                using (FileStream fs = new FileStream(filePath, FileMode.Append))
                    fs.Write(bytes, 0, bytes.Length);
            }
        }

19 View Source File : Anki.cs
License : MIT License
Project Creator : AnkiTools

private void CreateMediaFile()
        {
            string mediaFilePath = Path.Combine(_path, "media");

            if (File.Exists(mediaFilePath))
                File.Delete(mediaFilePath);

            using (FileStream fs = File.Create(mediaFilePath))
            {
                string data = "{";
                int i = 0;

                if (_mediaInfo != null)
                {
                    foreach (var item in _ankiItems)
                    {
                        if (_mediaInfo.extension == ".gif" && _mediaInfo.cultureInfo.Name == "zh-CN")
                            StrokeOrderHelper.DownloadImage(Path.Combine(_path, i.ToString()), item[_mediaInfo.field].ToString());
                        else if (_mediaInfo.extension == ".wav")
                            SynthetizerHelper.CreateAudio(Path.Combine(_path, i.ToString()), item[_mediaInfo.field].ToString(), _mediaInfo.cultureInfo, _mediaInfo.audioFormat);

                        data += "\"" + i.ToString() + "\": \"" + item[_mediaInfo.field] + _mediaInfo.extension + "\"";

                        if (i < _ankiItems.Count() - 1)
                            data += ", ";

                        i++;
                    }
                }
                data += "}";

                byte[] info = new UTF8Encoding(true).GetBytes(data);
                fs.Write(info, 0, info.Length);
                fs.Close();
            }
        }

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

public bool SaveConfiguration(string filename, string newline, bool whitespace)
		{
			// Kill the file if it exists
			if(File.Exists(filename) == true) File.Delete(filename);
			
			// Open file stream for writing
			FileStream fstream = File.OpenWrite(filename);
			
			// Create output structure and write to file
			string data = OutputConfiguration(newline, whitespace);
			byte[] baData= Encoding.UTF8.GetBytes(data);
			fstream.Write(baData, 0, baData.Length);
			fstream.Flush();
			fstream.Close();
			
			// Return true when done, false when errors occurred
			return !cpErrorResult;
		}

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

public bool SaveConfiguration(string filename, string newline, bool whitespace)
		{
			// Kill the file if it exists
			if(File.Exists(filename) == true) File.Delete(filename);
			
			// Open file stream for writing
			FileStream fstream = File.OpenWrite(filename);
			
			// Create output structure and write to file
			string data = OutputConfiguration(newline, whitespace);
			byte[] baData= Encoding.ASCII.GetBytes(data);
			fstream.Write(baData, 0, baData.Length);
			fstream.Flush();
			fstream.Close();
			
			// Return true when done, false when errors occurred
			if(cpErrorResult == 0) return true; else return false;
		}

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

void WritePackages()
        {
            //写入单个包
            void WritePackage(UnityWebRequest webRequest)
            {
                byte[] buff = webRequest.downloadHandler.data;
                if (buff != null && buff.Length > 0)
                {
                    this.fileStream.Write(buff, 0, buff.Length);
                    this.byteWrites += buff.Length;
                }

                Log.Debug($"write file Length:{byteWrites}");
            }

            //从第一个开始顺序写入
            while (this.dataRequests.Count > 0 && dataRequests[0].isDone)
            {
                UnityWebRequest first = dataRequests[0];
                dataRequests.RemoveAt(0);
                WritePackage(first);
                first.Dispose();
            }
        }

19 View Source File : AquesTalk.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void TextToWave(
            string textToSpeak,
            string waveFileName,
            AQTK_VOICE voice)
        {
            if (string.IsNullOrWhiteSpace(textToSpeak))
            {
                return;
            }

            if (this.SyntheDelegate == null ||
                this.FreeWaveDelegate == null)
            {
                return;
            }

            var wavePtr = IntPtr.Zero;
            var waveSize = 0;

            try
            {
                var chars = this.UTF16Encoding.GetBytes(textToSpeak);

                // テキストを音声データに変換する
                wavePtr = this.SyntheDelegate?.Invoke(
                    ref voice,
                    chars,
                    ref waveSize) ?? IntPtr.Zero;

                if (wavePtr == IntPtr.Zero ||
                    waveSize <= 0)
                {
                    return;
                }

                FileHelper.CreateDirectory(waveFileName);

                // 生成したwaveデータを読み出す
                var buff = new byte[waveSize];
                Marshal.Copy(wavePtr, buff, 0, (int)waveSize);
                using (var fs = new FileStream(waveFileName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(buff, 0, buff.Length);
                }
            }
            finally
            {
                if (wavePtr != IntPtr.Zero &&
                    waveSize != 0)
                {
                    this.FreeWaveDelegate?.Invoke(wavePtr);
                }
            }
        }

19 View Source File : YukkuriModel.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void TextToWave(
            string textToSpeak,
            string waveFileName,
            int speed)
        {
            if (string.IsNullOrWhiteSpace(textToSpeak))
            {
                return;
            }

            if (this.SynthesizeDelegate == null ||
                this.FreeWaveDelegate == null)
            {
                return;
            }

            var wavePtr = IntPtr.Zero;

            try
            {
                // テキストを音声データに変換する
                uint size = 0;
                wavePtr = this.SynthesizeDelegate.Invoke(
                    textToSpeak,
                    (ushort)speed,
                    ref size);

                if (wavePtr == IntPtr.Zero ||
                    size <= 0)
                {
                    return;
                }

                FileHelper.CreateDirectory(waveFileName);

                // 生成したwaveデータを読み出す
                var buff = new byte[size];
                Marshal.Copy(wavePtr, buff, 0, (int)size);
                using (var fs = new FileStream(waveFileName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(buff, 0, buff.Length);
                }
            }
            finally
            {
                if (wavePtr != IntPtr.Zero)
                {
                    this.FreeWaveDelegate.Invoke(wavePtr);
                }
            }
        }

19 View Source File : egsTools.cs
License : Apache License 2.0
Project Creator : AntonioDePau

private static Hed.Entry AddFile(string inputFolder, string filename, FileStream hedStream, FileStream pkgStream, bool shouldCompressData = false, bool shouldEncryptData = false)
        {
            var completeFilePath = Path.Combine(inputFolder, ORIGINAL_FILES_FOLDER_NAME, filename);
            var offset = pkgStream.Position;

            #region Data

            using var newFileStream = File.OpenRead(completeFilePath);

            var header = new EgsHdreplacedet.Header()
            {
                // CompressedLenght => -2: no compression and encryption, -1: no compression 
                CompressedLength = !shouldCompressData ? !shouldEncryptData ? -2 : -1 : 0,
                DecompressedLength = (int)newFileStream.Length,
                RemasteredreplacedetCount = 0,
                CreationDate = -1
            };

            var decompressedData = newFileStream.ReadAllBytes();
            var compressedData = decompressedData.ToArray();

            if (shouldCompressData)
            {
                compressedData = Helpers.CompressData(decompressedData);
                header.CompressedLength = compressedData.Length;
            }
			
			SDreplacedet sdreplacedet = new SDreplacedet(filename, decompressedData);
			
			if(sdreplacedet != null && !sdreplacedet.Invalid) header.RemasteredreplacedetCount = sdreplacedet.TextureCount;

            // Encrypt and write current file data in the PKG stream
            // The seed used for encryption is the original data header
            var seed = new MemoryStream();
            BinaryMapping.WriteObject<EgsHdreplacedet.Header>(seed, header);

            var encryptionSeed = seed.ReadAllBytes();
            var encryptedData = header.CompressedLength > -2 ? EgsEncryption.Encrypt(compressedData, encryptionSeed) : compressedData;

            // Write original file header
            BinaryMapping.WriteObject<EgsHdreplacedet.Header>(pkgStream, header);

			if (header.RemasteredreplacedetCount > 0)
			{
				// Create an "replacedet" to preplaced to ReplaceRemasteredreplacedets
				EgsHdreplacedet replacedet = new EgsHdreplacedet(header, decompressedData, encryptedData, encryptionSeed);
				ReplaceRemasteredreplacedets(inputFolder, filename, replacedet, pkgStream, encryptionSeed, encryptedData, sdreplacedet);
			}
			else
			{
				// Make sure to write the original file after remastered replacedets headers
				pkgStream.Write(encryptedData);
			}

            #endregion

            // Write a new entry in the HED stream
            var hedHeader = new Hed.Entry()
            {
                MD5 = Helpers.ToBytes(Helpers.CreateMD5(filename)),
                ActualLength = (int)newFileStream.Length,
                DataLength = (int)(pkgStream.Position - offset),
                Offset = offset
            };
			
            if (!Names.TryGetValue(Helpers.ToString(hedHeader.MD5), out var existingfilename)){
				File.AppendAllText("resources/custom_filenames.txt", filename + "\n");
            }

            BinaryMapping.WriteObject<Hed.Entry>(hedStream, hedHeader);

            return hedHeader;
        }

19 View Source File : egsTools.cs
License : Apache License 2.0
Project Creator : AntonioDePau

private static Hed.Entry ReplaceFile(
            string inputFolder,
            string filename,
            FileStream hedStream,
            FileStream pkgStream,
            EgsHdreplacedet replacedet,
            Hed.Entry originalHedHeader = null)
        {
            var completeFilePath = Path.Combine(inputFolder, ORIGINAL_FILES_FOLDER_NAME, filename);

            var offset = pkgStream.Position;
            var originalHeader = replacedet.OriginalreplacedetHeader;

            // Clone the original replacedet header
            var header = new EgsHdreplacedet.Header()
            {
                CompressedLength = originalHeader.CompressedLength,
                DecompressedLength = originalHeader.DecompressedLength,
                RemasteredreplacedetCount = originalHeader.RemasteredreplacedetCount,
                CreationDate = originalHeader.CreationDate
            };

            // Use the base original replacedet data by default
            var decompressedData = replacedet.OriginalData;
            var encryptedData = replacedet.OriginalRawData;
            var encryptionSeed = replacedet.Seed;

			SDreplacedet sdreplacedet = null;
            // We want to replace the original file
            if (File.Exists(completeFilePath))
            {
                Console.WriteLine($"Replacing original: {filename}!");

                using var newFileStream = File.OpenRead(completeFilePath);
                decompressedData = newFileStream.ReadAllBytes();
				
				sdreplacedet = new SDreplacedet(filename, decompressedData);
				
				if(sdreplacedet != null && !sdreplacedet.Invalid) header.RemasteredreplacedetCount = sdreplacedet.TextureCount;

                var compressedData = decompressedData.ToArray();
                var compressedDataLenght = originalHeader.CompressedLength;

                // CompressedLenght => -2: no compression and encryption, -1: no compression 
                if (originalHeader.CompressedLength > -1)
                {
                    compressedData = Helpers.CompressData(decompressedData);
                    compressedDataLenght = compressedData.Length;
                }

                header.CompressedLength = compressedDataLenght;
                header.DecompressedLength = decompressedData.Length;
                // Encrypt and write current file data in the PKG stream

                // The seed used for encryption is the original data header
                var seed = new MemoryStream();
                BinaryMapping.WriteObject<EgsHdreplacedet.Header>(seed, header);

                encryptionSeed = seed.ReadAllBytes();
                encryptedData = header.CompressedLength > -2 ? EgsEncryption.Encrypt(compressedData, encryptionSeed) : compressedData;
            }
			
            // Write original file header
            BinaryMapping.WriteObject<EgsHdreplacedet.Header>(pkgStream, header);

            var remasteredHeaders = new List<EgsHdreplacedet.RemasteredEntry>();

            // Is there remastered replacedets?
            if (header.RemasteredreplacedetCount > 0)
            {
                remasteredHeaders = ReplaceRemasteredreplacedets(inputFolder, filename, replacedet, pkgStream, encryptionSeed, encryptedData, sdreplacedet);
            }
            else
            {
                // Make sure to write the original file after remastered replacedets headers
                pkgStream.Write(encryptedData);
            }

            // Write a new entry in the HED stream
            var hedHeader = new Hed.Entry()
            {
                MD5 = Helpers.ToBytes(Helpers.CreateMD5(filename)),
                ActualLength = decompressedData.Length,
                DataLength = (int)(pkgStream.Position - offset),
                Offset = offset
            };

            // For unknown reason, some files have a data length of 0
            if (originalHedHeader.DataLength == 0)
            {
                Console.WriteLine($"{filename} => {originalHedHeader.ActualLength} ({originalHedHeader.DataLength})");

                hedHeader.ActualLength = originalHedHeader.ActualLength;
                hedHeader.DataLength = originalHedHeader.DataLength;
            }

            BinaryMapping.WriteObject<Hed.Entry>(hedStream, hedHeader);

            return hedHeader;
        }

19 View Source File : egsTools.cs
License : Apache License 2.0
Project Creator : AntonioDePau

private static List<EgsHdreplacedet.RemasteredEntry> ReplaceRemasteredreplacedets(string inputFolder, string originalFile, EgsHdreplacedet replacedet, FileStream pkgStream, byte[] seed, byte[] originalreplacedetData, SDreplacedet sdreplacedet)
        {
            var newRemasteredHeaders = new List<EgsHdreplacedet.RemasteredEntry>();
            var oldRemasteredHeaders = new List<EgsHdreplacedet.RemasteredEntry>();
            var relativePath = Helpers.GetRelativePath(originalFile, Path.Combine(inputFolder, ORIGINAL_FILES_FOLDER_NAME));
            var remasteredreplacedetsFolder = Path.Combine(inputFolder, REMASTERED_FILES_FOLDER_NAME, relativePath);

            var allRemasteredreplacedetsData = new MemoryStream();
            
            foreach (var remasteredreplacedetHeader in replacedet.RemasteredreplacedetHeaders.Values){
            	oldRemasteredHeaders.Add(remasteredreplacedetHeader);
            }

			//At the moment this only applies on fresh PKGs (or ones that haven't been patched with this modded MDLX before, otherwise we'd neet to replacedyse ALL MDLX files)
			if(sdreplacedet != null && !sdreplacedet.Invalid){
				File.AppendAllText("custom_hd_replacedets.txt", "HD replacedets for: " + originalFile + "\n");
				while(oldRemasteredHeaders.Count > sdreplacedet.TextureCount){
					File.AppendAllText("custom_hd_replacedets.txt", "Removing: -" + (oldRemasteredHeaders.Count-1) + ".dds\n");
					oldRemasteredHeaders.RemoveAt(oldRemasteredHeaders.Count-1);
				}
				while(oldRemasteredHeaders.Count < sdreplacedet.TextureCount){
					var newRemasteredreplacedetHeader = new EgsHdreplacedet.RemasteredEntry()
					{
						CompressedLength = 0,
						DecompressedLength = 0,
						Name = "-" + oldRemasteredHeaders.Count + ".dds",
						Offset = 0,
						OriginalreplacedetOffset = 0
					};
					File.AppendAllText("custom_hd_replacedets.txt", "Adding: -" + oldRemasteredHeaders.Count + ".dds\n");
					oldRemasteredHeaders.Add(newRemasteredreplacedetHeader);
				}
				File.AppendAllText("custom_hd_replacedets.txt", "\n");
			}
			
            // 0x30 is the size of this header
            var totalRemasteredreplacedetHeadersSize = oldRemasteredHeaders.Count() * 0x30;
            // This offset is relative to the original replacedet data
            var offset = totalRemasteredreplacedetHeadersSize + 0x10 + replacedet.OriginalreplacedetHeader.DecompressedLength;
			
            for(int i=0;i<oldRemasteredHeaders.Count;i++)
            {
				var remasteredreplacedetHeader = oldRemasteredHeaders[i];
                var filename = remasteredreplacedetHeader.Name;
                var replacedetFilePath = Path.Combine(remasteredreplacedetsFolder, filename);

                // Use base remastered replacedet data
                var replacedetData = replacedet.RemasteredreplacedetsDecompressedData.ContainsKey(filename) ? replacedet.RemasteredreplacedetsDecompressedData[filename] : new byte[]{};
                var decompressedLength = remasteredreplacedetHeader.DecompressedLength;
				var originalreplacedetOffset = remasteredreplacedetHeader.OriginalreplacedetOffset;
                if (File.Exists(replacedetFilePath))
                {
                    Console.WriteLine($"Replacing remastered file: {relativePath}/{filename}");

                    replacedetData = File.ReadAllBytes(replacedetFilePath);
                    decompressedLength = replacedetData.Length;
                    replacedetData = remasteredreplacedetHeader.CompressedLength > -1 ? Helpers.CompressData(replacedetData) : replacedetData;
                    replacedetData = remasteredreplacedetHeader.CompressedLength > -2 ? EgsEncryption.Encrypt(replacedetData, seed) : replacedetData;
					if(sdreplacedet != null && !sdreplacedet.Invalid) originalreplacedetOffset = sdreplacedet.Offsets[i];
                }
                else
                {
                    Console.WriteLine($"Keeping remastered file: {relativePath}/{filename}");
                    // The original file have been replaced, we need to encrypt all remastered replacedet with the new key
                    if (!seed.SequenceEqual(replacedet.Seed))
                    {
                        replacedetData = remasteredreplacedetHeader.CompressedLength > -1 ? Helpers.CompressData(replacedetData) : replacedetData;
                        replacedetData = remasteredreplacedetHeader.CompressedLength > -2 ? EgsEncryption.Encrypt(replacedetData, seed) : replacedetData;
						if(sdreplacedet != null && !sdreplacedet.Invalid && sdreplacedet.TextureCount >= i) originalreplacedetOffset = sdreplacedet.Offsets[i];
                    }else{
						replacedetData = replacedet.RemasteredreplacedetsCompressedData.ContainsKey(filename) ? replacedet.RemasteredreplacedetsCompressedData[filename] : new byte[]{};
					}
                }
                var compressedLength = remasteredreplacedetHeader.CompressedLength > -1 ? replacedetData.Length : remasteredreplacedetHeader.CompressedLength;

                var newRemasteredreplacedetHeader = new EgsHdreplacedet.RemasteredEntry()
                {
                    CompressedLength = compressedLength,
                    DecompressedLength = decompressedLength,
                    Name = filename,
                    Offset = offset,
                    OriginalreplacedetOffset = originalreplacedetOffset
                };

                newRemasteredHeaders.Add(newRemasteredreplacedetHeader);

                // Write replacedet header in the PKG stream
                BinaryMapping.WriteObject<EgsHdreplacedet.RemasteredEntry>(pkgStream, newRemasteredreplacedetHeader);

                // Don't write into the PKG stream yet as we need to write
                // all HD replacedets header juste after original file's data
                allRemasteredreplacedetsData.Write(replacedetData);

                // Make sure to align remastered replacedet data on 16 bytes
                if (replacedetData.Length % 0x10 != 0)
                {
                    allRemasteredreplacedetsData.Write(Enumerable.Repeat((byte)0xCD, 16 - (replacedetData.Length % 0x10)).ToArray());
                }

                offset += decompressedLength;
            }

            pkgStream.Write(originalreplacedetData);
            pkgStream.Write(allRemasteredreplacedetsData.ReadAllBytes());

            return newRemasteredHeaders;
        }

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

private static void ExtractResourceToFile(replacedembly a, string resourceName, string filename)
        {
            int n = 0;
            byte[] bytes = new byte[1024];
            using (Stream instream = a.GetManifestResourceStream(resourceName))
            {
                if (instream == null)
                    throw new ZipException(String.Format("missing resource '{0}'", resourceName));

                using (FileStream outstream = File.OpenWrite(filename))
                {
                    do
                    {
                        n = instream.Read(bytes, 0, bytes.Length);
                        outstream.Write(bytes, 0, n);
                    } while (n > 0);
                }
            }
        }

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

public void Save()
        {
            try
            {
                if (_stream is MemoryStream && _stream.Length > 0)
                {
                    //Close any open memorystream and "renew" then. This can occure if the package is saved twice. 
                    //The stream is left open on save to enable the user to read the stream-property.
                    //Non-memorystream streams will leave the closing to the user before saving a second time.
                    CloseStream();
                }

                Workbook.Save();
                if (File == null)
                {
                    if(Encryption.IsEncrypted)
                    {
                        var ms = new MemoryStream();
                        _package.Save(ms);
                        byte[] file = ms.ToArray(); 
                        EncryptedPackageHandler eph = new EncryptedPackageHandler();
                        var msEnc = eph.EncryptPackage(file, Encryption);
                        CopyStream(msEnc, ref _stream);
                    }   
                    else
                    {
                        _package.Save(_stream);
                    }
                    _stream.Flush();
                    _package.Close();
                }
                else
                {
                    if (System.IO.File.Exists(File.FullName))
                    {
                        try
                        {
                            System.IO.File.Delete(File.FullName);
                        }
                        catch (Exception ex)
                        {
                            throw (new Exception(string.Format("Error overwriting file {0}", File.FullName), ex));
                        }
                    }

                    _package.Save(_stream);
                    _package.Close();
                    if (Stream is MemoryStream)
                    {
                        var fi = new FileStream(File.FullName, FileMode.Create);
                        //EncryptPackage
                        if (Encryption.IsEncrypted)
                        {
                            byte[] file = ((MemoryStream)Stream).ToArray();
                            EncryptedPackageHandler eph = new EncryptedPackageHandler();
                            var ms = eph.EncryptPackage(file, Encryption);
                             
                            fi.Write(ms.ToArray(), 0, (int)ms.Length);
                        }
                        else
                        {                            
                            fi.Write(((MemoryStream)Stream).ToArray(), 0, (int)Stream.Length);
                        }
                        fi.Close();
                        fi.Dispose();
                    }
                    else
                    {
                        System.IO.File.WriteAllBytes(File.FullName, GetAsByteArray(false));
                    }
                }
            }
            catch (Exception ex)
            {
                if (File == null)
                {
                    throw;
                }
                else
                {
                    throw (new InvalidOperationException(string.Format("Error saving file {0}", File.FullName), ex));
                }
            }
        }

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

public void Save()
        {
            try
            {
                if (_stream is MemoryStream && _stream.Length > 0)
                {
                    //Close any open memorystream and "renew" then. This can occure if the package is saved twice. 
                    //The stream is left open on save to enable the user to read the stream-property.
                    //Non-memorystream streams will leave the closing to the user before saving a second time.
                    CloseStream();
                }

                Workbook.Save();
                if (File == null)
                {
                    if(Encryption.IsEncrypted)
                    {
                        var ms = new MemoryStream();
                        _package.Save(ms);
                        byte[] file = ms.ToArray(); 
                        EncryptedPackageHandler eph = new EncryptedPackageHandler();
                        var msEnc = eph.EncryptPackage(file, Encryption);
                        CopyStream(msEnc, ref _stream);
                    }   
                    else
                    {
                        _package.Save(_stream);
                    }
                    _stream.Flush();
                    _package.Close();
                }
                else
                {
                    if (System.IO.File.Exists(File.FullName))
                    {
                        try
                        {
                            System.IO.File.Delete(File.FullName);
                        }
                        catch (Exception ex)
                        {
                            throw (new Exception(string.Format("Error overwriting file {0}", File.FullName), ex));
                        }
                    }

                    _package.Save(_stream);
                    _package.Close();
                    if (Stream is MemoryStream)
                    {
                        var fi = new FileStream(File.FullName, FileMode.Create);
                        //EncryptPackage
                        if (Encryption.IsEncrypted)
                        {
                            byte[] file = ((MemoryStream)Stream).ToArray();
                            EncryptedPackageHandler eph = new EncryptedPackageHandler();
                            var ms = eph.EncryptPackage(file, Encryption);
                             
                            fi.Write(ms.ToArray(), 0, (int)ms.Length);
                        }
                        else
                        {                            
                            fi.Write(((MemoryStream)Stream).ToArray(), 0, (int)Stream.Length);
                        }
                        fi.Close();
                        fi.Dispose();
                    }
                    else
                    {
                        System.IO.File.WriteAllBytes(File.FullName, GetAsByteArray(false));
                    }
                }
            }
            catch (Exception ex)
            {
                if (File == null)
                {
                    throw;
                }
                else
                {
                    throw (new InvalidOperationException(string.Format("Error saving file {0}", File.FullName), ex));
                }
            }
        }

19 View Source File : LogService.cs
License : Apache License 2.0
Project Creator : AppRopio

private Task WriteAsync()
        {
            return Task.Run(() =>
            {
                try
                {
                    byte[] data = null;

                    lock (_logQueue)
                    {
                        data = _logQueue.Dequeue();
                    }

                    try
                    {
                        System.Diagnostics.Trace.WriteLine(Encoding.UTF8.GetString(data));
                    }
                    catch { }

                    var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

                    if (!Directory.Exists(folderPath))
                        Directory.CreateDirectory(folderPath);

                    var filePath = Path.Combine(folderPath, FILE_NAME);
                    FileStream fStream;

                    if (!File.Exists(filePath))
                    {
                        fStream = File.Create(filePath);

                        var creationData = Encoding.UTF8.GetBytes($"CreationTime: {DateTime.UtcNow}\n");
                        fStream.Write(creationData, 0, creationData.Length);

                        _cachedLogBytes = new List<byte>();
                    }
                    else
                    {
                        var fileInfo = new FileInfo(filePath);
                        if ((fileInfo.CreationTimeUtc - DateTime.UtcNow).Days > 7 || ((fileInfo.Length + data.Length) / (1024 * 1024)) >= 1)
                        {
                            File.Delete(filePath);

                            fStream = File.Create(filePath);

                            var creationData = Encoding.UTF8.GetBytes($"CreationTime: {DateTime.UtcNow}\n");
                            fStream.Write(creationData, 0, creationData.Length);

                            _cachedLogBytes = new List<byte>();
                        }
                        else
                            fStream = File.Open(filePath, FileMode.Append, FileAccess.Write);
                    }

                    fStream.Write(data, 0, data.Length);

                    fStream.Close();

                    _cachedLogBytes.AddRange(data);

                    if (!_readStarted)
                    {
                        lock (_logQueue)
                        {
                            if (_logQueue.Any())
                                WriteAsync();
                            else
                                _writeStarted = false;
                        }
                    }
                    else
                        _writeStarted = false;
                }
                catch
                { }
            }, _writeCTS.Token);
        }

See More Examples