public Write ( byte array, int offset, int count ) : void | ||
array | byte | |
offset | int | |
count | int | |
return | void |
static void EncodeFile(byte[] key, String sourceFile, string destFile) { // initialize keyed hash object HMACSHA1 hms = new HMACSHA1(key); // open filestreams to read in original file and write out coded file using(FileStream inStream = new FileStream(sourceFile,FileMode.Open)) using (FileStream outStream = new FileStream(destFile, FileMode.Create)) { // array to hold keyed hash value of original file byte[] hashValue = hms.ComputeHash(inStream); // reset instream ready to read original file contents from start inStream.Position = 0; // write keyed hash value to coded file outStream.Write(hashValue, 0, hashValue.Length); // copy data from original file to output file, 1K at a time int bytesRead; byte[] buffer = new byte[1024]; do { bytesRead = inStream.Read(buffer, 0, 1024); outStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); hms.Clear(); inStream.Close(); outStream.Close(); } }
private static void AddText(FileStream fs, string value) { byte[] info = new UTF8Encoding(true).GetBytes(value); fs.Write(info, 0, info.Length); byte[] newline = Encoding.ASCII.GetBytes(Environment.NewLine); fs.Write(newline, 0, newline.Length); }
private static void DisplayContent(HttpWebResponse response, string id) { Stream stream = response.GetResponseStream(); if (stream != null) { string filePath = "D:\\pic\\" + id + ".png"; FileStream fs = new FileStream(filePath, FileMode.Create); GZipStream gzip = new GZipStream(stream, CompressionMode.Decompress); byte[] bytes = new byte[1024]; int len; if ((len = gzip.Read(bytes, 0, bytes.Length)) > 0) { fs.Write(bytes, 0, len); } else { fs.Close(); File.Delete(filePath); throw new Exception(); } while ((len = gzip.Read(bytes, 0, bytes.Length)) > 0) { fs.Write(bytes, 0, len); } fs.Close(); } }
public void Save(string path) { using (var sw = new FileStream(path, FileMode.Create)) { var heightBytes = BitConverter.GetBytes(Height); sw.Write(heightBytes, 0, 4); var widthBytes = BitConverter.GetBytes(Width); sw.Write(widthBytes, 0, 4); var compressionLevelBytes = BitConverter.GetBytes(CompressionLevel); sw.Write(compressionLevelBytes, 0, 4); var frequencesPerBlockBytes = BitConverter.GetBytes(FrequencesPerBlock); sw.Write(frequencesPerBlockBytes, 0, 4); int blockSize = FrequencesPerBlock; for (int blockNum = 0; blockNum * blockSize < Frequences.Count; blockNum++) { for (int freqNum = 0; freqNum < blockSize; freqNum++) { var portion = BitConverter.GetBytes((short)Frequences[blockNum * blockSize + freqNum]); sw.Write(portion, 0, portion.Length); } } } }
public void BluRaySupWriteAndReadTwoBitmaps() { var fileName = Guid.NewGuid() + ".sup"; using (var binarySubtitleFile = new FileStream(fileName, FileMode.Create)) { var brSub = new BluRaySupPicture { StartTime = 0, EndTime = 1000, Width = 1080, Height = 720 }; var buffer = BluRaySupPicture.CreateSupFrame(brSub, new Bitmap(100, 20), 10, 25, 10, ContentAlignment.BottomCenter); binarySubtitleFile.Write(buffer, 0, buffer.Length); brSub.StartTime = 2000; brSub.EndTime = 3000; buffer = BluRaySupPicture.CreateSupFrame(brSub, new Bitmap(100, 20), 10, 25, 10, ContentAlignment.BottomCenter); binarySubtitleFile.Write(buffer, 0, buffer.Length); } var log = new StringBuilder(); var subtitles = BluRaySupParser.ParseBluRaySup(fileName, log); Assert.AreEqual(2, subtitles.Count); }
// Computes a keyed hash for a source file and creates a target file with the keyed hash // prepended to the contents of the source file. public static void SignFile(byte[] key, String sourceFile, String destFile) { // Initialize the keyed hash object. using (HMACSHA512 hmac = new HMACSHA512(key)) { using (FileStream inStream = new FileStream(sourceFile, FileMode.Open)) { using (FileStream outStream = new FileStream(destFile, FileMode.Create)) { // Compute the hash of the input file. byte[] hashValue = hmac.ComputeHash(inStream); // Reset inStream to the beginning of the file. inStream.Position = 0; // Write the computed hash value to the output file. outStream.Write(hashValue, 0, hashValue.Length); // Copy the contents of the sourceFile to the destFile. int bytesRead; // read 1K at a time byte[] buffer = new byte[1024]; do { // Read from the wrapping CryptoStream. bytesRead = inStream.Read(buffer, 0, 1024); outStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); } } } }
private static void WriteFile(string sFilename, HTTPHeaders oH, byte[] arrData) { FileStream fileStream = new FileStream(sFilename, FileMode.Create, FileAccess.Write); if (oH != null) { HTTPRequestHeaders hTTPRequestHeader = oH as HTTPRequestHeaders; if (hTTPRequestHeader == null) { HTTPResponseHeaders hTTPResponseHeader = oH as HTTPResponseHeaders; if (hTTPResponseHeader != null) { byte[] byteArray = hTTPResponseHeader.ToByteArray(true, true); fileStream.Write(byteArray, 0, (int)byteArray.Length); } } else { byte[] numArray = hTTPRequestHeader.ToByteArray(true, true, true); fileStream.Write(numArray, 0, (int)numArray.Length); } } if (arrData != null) { fileStream.Write(arrData, 0, (int)arrData.Length); } fileStream.Close(); }
protected void DoCss(string modulePath, string moduleName) { List<string> cssFiles = new List<string>(); ScanDir(new DirectoryInfo(modulePath), "*.css", ref cssFiles); ScanDir(new DirectoryInfo(modulePath), "*.less", ref cssFiles); FileStream file = new FileStream(_pathBuild + "/" + moduleName + ".css", FileMode.Create); foreach (string cssFile in cssFiles) { if (cssFile.EndsWith(".less")) { string fileText = ""; fileText = File.ReadAllText(cssFile); fileText = Less.Parse(fileText); byte[] b1 = Encoding.UTF8.GetBytes(fileText); file.Write(b1,0,b1.Length); } else { int Count = 0; byte[] buffer = new byte[1024]; FileStream FS = new FileStream(cssFile, FileMode.Open, FileAccess.Read, FileShare.Read); while (FS.Position < FS.Length) { // Читаем данные из файла Count = FS.Read(buffer, 0, buffer.Length); // И передаем их клиенту file.Write(buffer, 0, Count); } FS.Close(); } } file.Close(); }
//, GameSet set) internal void SaveGameSetToFile(string filePath) { using (FileStream fs = new FileStream(filePath, FileMode.Create)) { //write SET file header fs.Write(BitConverter.GetBytes(this._recordCount), 0, 2); foreach (DatabaseContainer db in this.DatabaseContainers) { fs.Write(Encoding.GetEncoding(1252).GetBytes(db.Name.PadRight(_rowNameSize, (char) 0x0)), 0, _rowNameSize); fs.Write(BitConverter.GetBytes(Convert.ToInt32(db.Offset)), 0, 4); } //write SET file header-trailer (9 nulls followed by int filesize). write size after writing DBFs. for (int i = 0; i < 13; i++) fs.WriteByte(0x0); long fileSizeBookmark = fs.Position - 4; //write out DBFs foreach (DatabaseContainer db in this.DatabaseContainers) { #if DEBUG //writes out individual DBFs... easier to inspect SFRAME, etc string path = this._dbfDirectory + "test"; Directory.CreateDirectory(path); db.DbfFileObject.WriteAndClose(path); #endif db.DbfFileObject.WriteToStream(fs); } fs.Position = fileSizeBookmark; int fileSize = (int) fs.Length; fs.Write(BitConverter.GetBytes(fileSize), 0, 4); } }
private void ReceiveFile(object obj) { string msg = (string)obj; string savePath = msg.Split(',')[0]; int len = int.Parse(msg.Split(',')[1]); FileStream fileReceive = new FileStream(savePath, FileMode.Create, FileAccess.Write); int bufferSize = Clients.client_FileTransport.ReceiveBufferSize; byte[] buffer = new byte[bufferSize]; //定义缓冲区 int left = len; //接收数据 while (left > 0) { if (left > buffer.Length) { Clients.netStream_FileTransport.Read(buffer, 0, buffer.Length); fileReceive.Write(buffer, 0, buffer.Length); left -= bufferSize; int value = (bufferSize - left) / len; SetProgress(value); } else { Clients.netStream_FileTransport.Read(buffer, 0, left); fileReceive.Write(buffer, 0, left); left -= bufferSize; SetProgress(100); } } fileReceive.Close(); }
public static void Save(string fileName, Subtitle subtitle) { using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { byte[] buffer = { 0x38, 0x35, 0x30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x30, 0x30, 0x30, 0x39 }; fs.Write(buffer, 0, buffer.Length); for (int i = 0; i < 0xde; i++) fs.WriteByte(0); string numberOfLines = subtitle.Paragraphs.Count.ToString("D5"); buffer = Encoding.ASCII.GetBytes(numberOfLines + numberOfLines + "001"); fs.Write(buffer, 0, buffer.Length); for (int i = 0; i < 0x15; i++) fs.WriteByte(0); buffer = Encoding.ASCII.GetBytes("11"); fs.Write(buffer, 0, buffer.Length); while (fs.Length < 1024) fs.WriteByte(0); int subtitleNumber = 0; foreach (Paragraph p in subtitle.Paragraphs) { WriteSubtitleBlock(fs, p, subtitleNumber); subtitleNumber++; } } }
// Export data public static void Export(byte[] data) { using (SaveFileDialog sfd = new SaveFileDialog()) { sfd.Filter = "Dropset Data|*.dat"; sfd.Title = "Export Dropset Data"; sfd.AddExtension = true; sfd.RestoreDirectory = true; sfd.OverwritePrompt = true; DialogResult result = sfd.ShowDialog(); if (result == DialogResult.OK) { try { using (FileStream outstream = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write)) { outstream.Write(new byte[] { 0x50, 0x50, 0x46, 0x44, 0x53, 0x45 }, 0, 6); outstream.Write(data, 0, data.Length); outstream.Close(); } MessageBox.Show("Dropset data exported successfully.", "Export Successful"); } catch { MessageBox.Show("An error occured when writing the dropset data.", "Export Unsuccessful"); } } } }
public static void WriteString(FileStream fs, string s) { if (s == null) s = ""; fs.Write(BitConverter.GetBytes((int)s.Length), 0, 4); fs.Write(GetBytes(s), 0, s.Length); }
// Computes a keyed hash for a source file, creates a target file with the keyed hash // prepended to the contents of the source file, then decrypts the file and compares // the source and the decrypted files. public static void EncodeFile(byte[] key, String sourceFile, String destFile) { // Initialize the keyed hash object. HMACSHA256 myhmacsha256 = new HMACSHA256(key); FileStream inStream = new FileStream(sourceFile, FileMode.Open); FileStream outStream = new FileStream(destFile, FileMode.Create); // Compute the hash of the input file. byte[] hashValue = myhmacsha256.ComputeHash(inStream); // Reset inStream to the beginning of the file. inStream.Position = 0; // Write the computed hash value to the output file. outStream.Write(hashValue, 0, hashValue.Length); // Copy the contents of the sourceFile to the destFile. int bytesRead; // read 1K at a time byte[] buffer = new byte[1024]; do { // Read from the wrapping CryptoStream. bytesRead = inStream.Read(buffer, 0, 1024); outStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); myhmacsha256.Clear(); // Close the streams inStream.Close(); outStream.Close(); return; }
public void doBackUp() { try { string path = @"C:\"; string newpath = System.IO.Path.Combine(path, "BackUpLocation"); Directory.CreateDirectory(newpath); FileStream fmdf = new FileStream(mdf, FileMode.Open, FileAccess.Read); FileStream fldf = new FileStream(ldf, FileMode.Open, FileAccess.Read); FileStream fbak = new FileStream(bak, FileMode.Create, FileAccess.Write); byte[] fmcontent = new byte[fmdf.Length]; fmdf.Read(fmcontent, 0, (int)fmdf.Length); fbak.Write(fmcontent, 0, (int)fmdf.Length); byte[] sym = new byte[3]; sym[0] = (byte)'$'; sym[1] = (byte)'*'; sym[2] = (byte)'^'; fbak.Write(sym, 0, 3); byte[] flcontent = new byte[fldf.Length]; fldf.Read(flcontent, 0, (int)fldf.Length); fbak.Write(flcontent, 0, (int)fldf.Length); fbak.Flush(); fbak.Close(); fmdf.Close(); fldf.Close(); } catch (Exception ex) { throw ex; } }
//Đưa SecretKey vào File của thuật toán 3DES public void AddSecretKeytoFile(string inputFile) { //Add SecretKey to File; if (File.Exists(inputFile)) { FileStream fsOpen = new FileStream(inputFile, FileMode.Open, FileAccess.ReadWrite); try { byte[] content = new byte[fsOpen.Length]; fsOpen.Read(content, 0, content.Length); //string sContent = System.Text.Encoding.UTF8.GetString(content); //noi dung bang string //byte[] plainbytesCheck = System.Text.Encoding.UTF8.GetBytes(sContent); byte[] plainbytesKey = new UTF8Encoding(true).GetBytes(m_EncryptedSecretKey + "\r\n"); fsOpen.Seek(0, SeekOrigin.Begin); fsOpen.Write(plainbytesKey, 0, plainbytesKey.Length); fsOpen.Flush(); fsOpen.Write(content, 0, content.Length); fsOpen.Flush(); fsOpen.Close(); } catch { fsOpen.Close(); } } }
public void Encrypt(string filename) { FileStream fsInput = new FileStream(filename, FileMode.Open, FileAccess.Read); FileStream fsOutput = new FileStream(filename + ".crypt", FileMode.Create, FileAccess.Write); AesCryptoServiceProvider Aes = new AesCryptoServiceProvider(); Aes.KeySize = 128; Aes.GenerateIV(); Aes.GenerateKey(); byte[] output = _algorithm_asym.Encrypt(Aes.Key, false); fsOutput.Write(output, 0, 256); output = _algorithm_asym.Encrypt(Aes.IV, false); fsOutput.Write(output, 0, 256); ICryptoTransform encrypt = Aes.CreateEncryptor(); CryptoStream cryptostream = new CryptoStream(fsOutput, encrypt, CryptoStreamMode.Write); byte[] bytearrayinput = new byte[fsInput.Length - 1]; fsInput.Read(bytearrayinput, 0, bytearrayinput.Length); cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length); fsInput.Close(); fsOutput.Close(); }
public MovieWriter(string filepath, MovieId id, bool UseExistingFile) { file = new FileInfo(filepath); if (file.Exists && UseExistingFile) { using (FileStream input = new FileStream(filepath, FileMode.Open, FileAccess.Read)) fs = new FrameScanner(input); if (fs.HeaderOkay) output = new FileStream(filepath, FileMode.Open, FileAccess.ReadWrite); } else { output = new FileStream(filepath, FileMode.Create, FileAccess.Write); output.Write(Encoding.ASCII.GetBytes("MMDb"), 0, 4); output.WriteByte((byte)FileVersions.First.Major); output.WriteByte((byte)FileVersions.First.Minor); output.Write(BitConverter.GetBytes(id.Id), 0, 4); output.Close(); using (FileStream input = new FileStream(filepath, FileMode.Open, FileAccess.Read)) fs = new FrameScanner(input); output = new FileStream(filepath, FileMode.Open, FileAccess.Write); } }
public void Encrypt(string key) { var stream = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); // decido quanti byte di inizio file criptare // ovviamente devo tener conto della dimensione del file int headerSize = 254; if (headerSize > stream.Length) headerSize = (int)stream.Length; var firstBytes = new byte[headerSize]; stream.Read(firstBytes, 0, firstBytes.Length); // crittografa il primo blocco di N bytes var crypto = RijndaelService.EncryptBytes(firstBytes, key); // leggi tutto il contenuto restante byte[] bytes = new byte[stream.Length - firstBytes.Length]; stream.Read(bytes, 0, bytes.Length); stream.Close(); stream.Dispose(); // LA situazione ora è definita da // crypto: primi N bytes criptati // bytes: i restanti bytes del file, normali stream = new FileStream(Filename, FileMode.Create); // All'inizio del blocco specifica il numero dei byte adibiti all'header section stream.Write(BitConverter.GetBytes(crypto.Length), 0, sizeof(int)); stream.Write(crypto, 0, crypto.Length); stream.Write(bytes, 0, bytes.Length); stream.Close(); stream.Dispose(); }
public static void Main(string[] args) { string SCRATCH_FILES_PATH = "ziptest"; string scratchPath = "ziptest.zip"; using (var archive = ZipArchive.Create()) { DirectoryInfo di = new DirectoryInfo(SCRATCH_FILES_PATH); foreach (var fi in di.GetFiles()) { archive.AddEntry(fi.Name, fi.OpenRead(), true); } FileStream fs_scratchPath = new FileStream(scratchPath, FileMode.OpenOrCreate, FileAccess.Write); archive.SaveTo(fs_scratchPath, CompressionType.Deflate); fs_scratchPath.Close(); //archive.AddAllFromDirectory(SCRATCH_FILES_PATH); //archive.SaveTo(scratchPath, CompressionType.Deflate); using (FileStream fs = new FileStream("ziphead.zip", FileMode.OpenOrCreate, FileAccess.ReadWrite)) { MyHead mh = new MyHead(); byte[] headData = mh.Create(); fs.Write(headData, 0, headData.Length); // SharpCompress.IO.OffsetStream ofs = new IO.OffsetStream(fs, fs.Position); archive.SaveTo(ofs, CompressionType.Deflate); } } //write my zipfile with head data using (FileStream fs = new FileStream("mypack.data.zip", FileMode.Create, FileAccess.ReadWrite, FileShare.Read)) { MyHead mh = new MyHead(); byte[] headData = mh.Create(); fs.Write(headData, 0, headData.Length); using (FileStream fs2 = new FileStream(scratchPath, FileMode.Open, FileAccess.Read)) { byte[] buf = new byte[1024]; int rc = 0; while ((rc = fs2.Read(buf, 0, buf.Length)) > 0) { fs.Write(buf, 0, rc); } } } // //read my zip file with head // using (FileStream fs = new FileStream("mypack.data.zip", FileMode.Open, FileAccess.Read, FileShare.Read)) { byte[] buf = new byte[1024]; int offset = fs.Read(buf, 0, buf.Length); System.Diagnostics.Debug.Assert(offset == 1024); //fs.Position = 0L; SharpCompress.IO.OffsetStream substream = new SharpCompress.IO.OffsetStream(fs, offset); ZipArchive zip = ZipArchive.Open(substream, Options.KeepStreamsOpen);//cann't read //ZipArchive zip = ZipArchive.Open(fs, Options.None); //will throw exption //ZipArchive zip = ZipArchive.Open(fs, Options.KeepStreamsOpen);//cann't read foreach (ZipArchiveEntry zf in zip.Entries) { Console.WriteLine(zf.Key); //bug:the will not none in zipfile } int jjj = 0; jjj++; } }
public void dump(string path) { string fname=Path.Combine(path,Path.GetFileName(filename)); FileStream fs=new FileStream(fname,FileMode.Create); fs.Write(data,0,data.Length); fs.Write(footer,0,footer.Length); fs.Close(); }
public static void SaveLUT(string file, Color32[] lut) { if (lut.Length != 256) return; using (FileStream fs = new FileStream(file, FileMode.Create)) { fs.Write(lut.Select(color => color.R).ToArray(), 0, lut.Length); fs.Write(lut.Select(color => color.G).ToArray(), 0, lut.Length); fs.Write(lut.Select(color => color.B).ToArray(), 0, lut.Length); } }
public bool Decrypt(string key, bool ownermode = true) { string password = key; var aglService = new FileAGLService(Filename); string decryptoAGL = string.Empty; if (aglService.Access(key, out decryptoAGL)) { if (decryptoAGL.Contains(FileAGLService.SecurityPhrase + ":")) password = decryptoAGL.Replace(FileAGLService.SecurityPhrase + ":", string.Empty); } else return false; int aglSize = aglService.Size(); var stream = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); // Ottieni la lunghezza dell'header stream.Seek(0, SeekOrigin.Begin); byte[] headerSizeBytes = new byte[sizeof(int)]; stream.Read(headerSizeBytes, 0, headerSizeBytes.Length); int headerSize = BitConverter.ToInt32(headerSizeBytes, 0); // leggi l'header var headerBytes = new byte[headerSize]; stream.Read(headerBytes, 0, headerBytes.Length); // decripta l'header byte[] decrypto; try { decrypto = RijndaelService.DecryptBytes(headerBytes, password); Key = password; } catch (Exception) { return false; } // se è riuscito a decriptarlo, sostituisci il file con quello originale, rimuovendo anchel'AGL var bytes = new byte[stream.Length - sizeof(int) - headerBytes.Length - aglSize]; stream.Read(bytes, 0, bytes.Length); stream.Close(); stream.Dispose(); // Ripristina il file stream = new FileStream(Filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); // All'inizio del blocco specifica il numero dei byte adibiti all'header section stream.Write(decrypto, 0, decrypto.Length); stream.Write(bytes, 0, bytes.Length); stream.Close(); stream.Dispose(); return true; }
public void NegativeOffsetThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { Assert.Throws<ArgumentOutOfRangeException>("offset", () => fs.Write(new byte[1], -1, 1)); // array is checked first Assert.Throws<ArgumentNullException>("array", () => fs.Write(null, -1, 1)); } }
public static void ConvertPNGtoTP(Stream stream, string tpPath) { using (FileStream fs = new FileStream(tpPath, FileMode.Create, FileAccess.Write, FileShare.Read)) { fs.Write(BitConverter.GetBytes(1), 0, 4); fs.Write(BitConverter.GetBytes(21), 0, 4); fs.Write(BitConverter.GetBytes((int)stream.Length), 0, 4); fs.Seek(9, SeekOrigin.Current); stream.CopyStream(fs); } }
public void Serialize(FileStream f) { f.Write(BitConverter.GetBytes(Neighbors.Length), 0, 4); foreach (int neighbor in Neighbors) { f.Write(BitConverter.GetBytes(neighbor), 0, 4); } f.Write(BitConverter.GetBytes(position.X), 0, 4); f.Write(BitConverter.GetBytes(position.Y), 0, 4); f.Write(BitConverter.GetBytes(position.Z), 0, 4); }
/// <summary> /// Encodes unencoded bytes and writes them to the FileStream /// </summary> /// <param name="w">FileStream to write to</param> /// <param name="ride">Unencoded bytes</param> public static void Write(FileStream w, byte[] ride) { byte[] encodedBytes = Encode(ride); w.Write(encodedBytes, 0, encodedBytes.Length); uint checksum = Checksum(encodedBytes); byte[] checksumBytes = BitConverter.GetBytes(checksum); w.Write(checksumBytes, 0, checksumBytes.Length); w.Flush(); }
public virtual void Test1() { var raf = new FileStream("testBigFile", FileMode.OpenOrCreate); long l = 2 * 1024000; Println(l); raf.Seek(l, SeekOrigin.Begin); for (var i = 0; i < 1024000; i++) raf.Write(new byte[] {0}, 0, 1); raf.Write(new byte[] {0}, 0, 1); raf.Close(); }
public static void Save(CurrentIDs currentIDs) { byte[] arrEncryptByte = Serialize.EncryptToBytes(currentIDs); byte[] arrLength = PubHelper.intToByte(arrEncryptByte.Length); //将长度(整数)保存在4个元素的字节数组中 lock (GlobalPool.Lock) { FileStream fs = new FileStream(Application.StartupPath + "\\config.ini", FileMode.OpenOrCreate); fs.Write(arrLength, 0, arrLength.Length); fs.Write(arrEncryptByte, 0, arrEncryptByte.Length); fs.Close(); } }
public static int serialMessageInfo(string path, byte[] content) { using (System.IO.FileStream fs = System.IO.File.OpenWrite(path)) { int length = content.Length; byte[] buffer = new byte[length + 4]; writeInt32Byte(buffer, length, 0); System.Buffer.BlockCopy(content, 0, buffer, 4, length); //System.Array.Copy(content, 0, buffer, 4, length); fs.Seek(0, System.IO.SeekOrigin.End); fs.Write(buffer, 0, length + 4); fs.Flush(); return(length); } }
public static void SaveStaticData(System.IO.FileStream fs) { int realCount = 0; var data = new List <byte>(); if (crewsList.Count > 0) { foreach (var c in crewsList) { if (c != null) { data.AddRange(c.Save()); realCount++; } } } fs.Write(System.BitConverter.GetBytes(realCount), 0, 4); if (realCount > 0) { var dataArray = data.ToArray(); fs.Write(dataArray, 0, dataArray.Length); } fs.Write(System.BitConverter.GetBytes(nextID), 0, 4); }
public void Save(System.IO.FileStream fs) { var ppos = plane.pos; fs.WriteByte(ppos.x); // 0 fs.WriteByte(ppos.y); // 1 fs.WriteByte(ppos.z); //2 fs.WriteByte(plane.faceIndex); //3 // fs.WriteByte((byte)categoriesCatalog[0]); // 4 fs.WriteByte((byte)categoriesCatalog[1]); //5 fs.WriteByte((byte)categoriesCatalog[2]); // 6 fs.WriteByte(level); //7 fs.WriteByte(cultivating ? (byte)1 : (byte)0); //8 fs.Write(System.BitConverter.GetBytes(lifepower), 0, 4); // 9-12 }
//jar(Resources folder xx.bytes) image to out file public static string getResourcesBytesToOutFile(string _filename) { string _imagePath = Application.persistentDataPath + "/" + _filename + ".png"; if (!System.IO.File.Exists(_imagePath)) { TextAsset _w = Resources.Load(_filename) as TextAsset; if (_w.bytes != null) { System.IO.FileStream _fs = new System.IO.FileStream(_imagePath, System.IO.FileMode.Create); _fs.Write(_w.bytes, 0, _w.bytes.Length); _fs.Close(); } } return(_imagePath); }
public void SaveStreamToFile(string fileFullPath, System.IO.Stream stream) { if (stream.Length == 0) { return; } // Create a FileStream object to write a stream to a file using (System.IO.FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length)) { // Fill the bytes[] array with the stream data byte[] bytesInStream = new byte[stream.Length]; stream.Read(bytesInStream, 0, (int)bytesInStream.Length); // Use FileStream object to write to the specified file fileStream.Write(bytesInStream, 0, bytesInStream.Length); } }
public void Save(System.IO.FileStream fs) { fs.Write(System.BitConverter.GetBytes(newWindVector.x), 0, 4); // 0 - 3 fs.Write(System.BitConverter.GetBytes(newWindVector.y), 0, 4); // 4 - 7 fs.Write(System.BitConverter.GetBytes(windVector.x), 0, 4); // 8 - 11 fs.Write(System.BitConverter.GetBytes(windVector.y), 0, 4); // 12 - 15 fs.Write(System.BitConverter.GetBytes(environmentalConditions), 0, 4); // 16 - 19 fs.Write(System.BitConverter.GetBytes(windTimer), 0, 4); // 20 - 23 //сохранение декораций? //save environment }
/// <summary> /// 更新本地配置 /// </summary> void UpdateLocalVersionFile() { if (NeedUpdateLocalVesionfile) { StringBuilder versions = new StringBuilder(); foreach (var item in ServerResVersion) { versions.Append(item.Key).Append(",").Append(item.Value).Append("\n"); } System.IO.FileStream stream = new System.IO.FileStream(LOCAL_RES_PATH + VERSION_FILE, System.IO.FileMode.Create); byte[] data = Encoding.UTF8.GetBytes(versions.ToString()); stream.Write(data, 0, data.Length); stream.Flush(); stream.Close(); } StartCoroutine(Show()); }
static public int Write(IntPtr l) { try { System.IO.FileStream self = (System.IO.FileStream)checkSelf(l); System.Byte[] a1; checkArray(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); self.Write(a1, a2, a3); pushValue(l, true); return(1); } catch (Exception e) { return(error(l, e)); } }
void PackTextures(int padding) { mTexturesToPack = new Texture2D[mProcessed.Count]; for (int i = 0; i < mProcessed.Count; i++) { mTexturesToPack[i] = mProcessed[i].image; } Texture2D texture = new Texture2D(4, 4); Rect[] textureRectangles = texture.PackTextures(mTexturesToPack, padding); int texWidth = texture.width; int texHeight = texture.height; byte[] bytes = texture.EncodeToPNG(); System.IO.FileStream fs = System.IO.File.Create(AssetDatabase.GetAssetPath(mOutputImage)); fs.Write(bytes, 0, bytes.Length); fs.Close(); UnityEngine.Object.DestroyImmediate(texture); bytes = null; AssetDatabase.Refresh(); for (int i = 0; i < mProcessed.Count; i++) { var p = mProcessed[i]; var r = textureRectangles[i]; int originX = (int)(r.x * texWidth) + p.border; int originY = (int)(r.y * texHeight) + p.border; foreach (var q in p.quads) { SpriteOutput output = new SpriteOutput(); output.name = q.name; output.x = originX + q.x; output.y = originY + q.y; output.w = q.w; output.h = q.h; mOutputs.Add(output); } } }
/// <summary> /// 下载文件 /// </summary> /// <param name="URL">文件URL</param> /// <param name="filename">保存到本地名称(如:D:\App\App.exe)</param> /// <param name="prog">进度条控件名</param> /// <param name="label1">显示进度文字控件</param> /// <returns></returns> public static string DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1) { string result = "下载失败"; float percent = 0; try { System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); long totalBytes = myrp.ContentLength; if (prog != null) { prog.Maximum = (int)totalBytes; } System.IO.Stream st = myrp.GetResponseStream(); System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create); long totalDownloadedByte = 0; byte[] by = new byte[1024]; int osize = st.Read(by, 0, (int)by.Length); while (osize > 0) { totalDownloadedByte = osize + totalDownloadedByte; System.Windows.Forms.Application.DoEvents(); so.Write(by, 0, osize); if (prog != null) { prog.Value = (int)totalDownloadedByte; } osize = st.Read(by, 0, (int)by.Length); percent = (float)totalDownloadedByte / (float)totalBytes * 100; label1.Text = "下载进度:" + percent.ToString() + "%"; System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息 } so.Close(); st.Close(); result = ""; } catch (System.Exception ex) { result = "下载失败:" + ex.Message; } return(result); }
override public void Save(System.IO.FileStream fs) { if (workplace == null) { StopWork(true); return; } else { var pos = workplace.pos; fs.WriteByte((byte)WorksiteType.GatherSite); fs.WriteByte(pos.x); fs.WriteByte(pos.y); fs.WriteByte(pos.z); fs.WriteByte(workplace.faceIndex); fs.Write(System.BitConverter.GetBytes(destructionTimer), 0, 4); SerializeWorksite(fs); } }
String storeProfileImage(String _userImage, String _userID) { string profileImgURL = ""; if (_userImage != "") { string sSavePath = "App_Resources/"; System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding(); System.Text.Decoder utf8Decode = encoder.GetDecoder(); byte[] ret = Convert.FromBase64String(_userImage); // Save the stream to disk System.IO.FileStream newFile = new System.IO.FileStream(Server.MapPath(sSavePath + _userID + ".jpg"), System.IO.FileMode.Create); newFile.Write(ret, 0, ret.Length); newFile.Close(); profileImgURL = "http://192.168.69.1/MTutorService/App_Resources/" + _userID + ".jpg"; } return(profileImgURL); }
static void CheckAllFiles() { string logfile = GetLogPath() + "/error.log"; using (System.IO.FileStream fs = System.IO.File.Open(logfile, System.IO.FileMode.OpenOrCreate)) { foreach (var item in allExistImages.Values) { string path = GetEgretRootPath() + "/resource/" + item; if (System.IO.File.Exists(path) == false) { byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes("资源文件不存在:" + path + "\n\r"); fs.Write(bytes, 0, bytes.Length); } } fs.Flush(); fs.Close(); } }
//public static void serialMultiMessageInfo(string path, LuaTable table, int size) //{ // using (System.IO.FileStream fs = System.IO.File.OpenWrite(path)) // { // int length = table.Length; // size = size + 4 * length; // byte[] totalbuffer = new byte[size]; // byte[] current = null; // int offset = 0; // int msgLength = 0; // for (int index = 1; index <= length; index++) // { // current = table[index] as byte[]; // msgLength = current.Length; // writeInt32Byte(totalbuffer, msgLength, offset); // System.Buffer.BlockCopy(current, 0, totalbuffer, offset + 4, msgLength); // //System.Array.Copy(content, 0, totalbuffer, offset + 4, msgLength); // offset = offset + 4 + msgLength; // } // fs.Seek(0, System.IO.SeekOrigin.End); // fs.Write(totalbuffer, 0, size); // fs.Flush(); // } //} public static void addBufferAndSerialMsgInfo(string path, byte[] buffer, bool lastWrite) { if (buffer == null || buffer.Length == 0) { return; } writeInt32Byte(lengthBuffer, buffer.Length, 0); allMsgBuffers.AddRange(lengthBuffer); allMsgBuffers.AddRange(buffer); if (lastWrite) { using (System.IO.FileStream fs = System.IO.File.OpenWrite(path)) { fs.Seek(0, System.IO.SeekOrigin.End); fs.Write(allMsgBuffers.ToArray(), 0, allMsgBuffers.Count); fs.Flush(); } allMsgBuffers.Clear(); } }
// Update is called once per frame void Update() { if (!recording) { return; } string line = ""; line = string.Concat(line, System.DateTime.Now.ToString("hh mm ss ff ")); line = string.Concat(line, username); line = string.Concat(line, " "); line = string.Concat(line, Time.time); line = string.Concat(line, " "); line = string.Concat(line, Time.deltaTime); line = string.Concat(line, " "); line = string.Concat(line, Input.GetAxis("Vertical")); line = string.Concat(line, " "); line = string.Concat(line, 0); line = string.Concat(line, " "); line = string.Concat(line, acceleration); line = string.Concat(line, " "); line = string.Concat(line, stopping); line = string.Concat(line, " "); line = string.Concat(line, seconds); //line = string.Concat(line, Time.deltaTime); //Debug.Log("Linea a escribir"); //Debug.Log(line); line = string.Concat(line, "\n"); oFileStream.Write(System.Text.Encoding.UTF8.GetBytes(line), 0, line.Length); if (end) { recording = false; oFileStream.Close(); } }
private void button1_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.InitialDirectory = "D:/"; saveFileDialog.Filter = "avi视频文件(*.avi)|*.avi|mp4视频文件(*.mp4)|*.mp4"; String time = DateTime.Now.ToString("yyyy_MM_dd"); saveFileDialog.FileName = "屏幕录制" + time; saveFileDialog.FilterIndex = 2; saveFileDialog.RestoreDirectory = true; if (saveFileDialog.ShowDialog() == DialogResult.OK) { String localFilePath = saveFileDialog.FileName.ToString(); System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog.OpenFile();//输出文件 fs.Write(System.Text.Encoding.ASCII.GetBytes(localFilePath), 0, localFilePath.Length); fs.Flush(); fs.Close(); } }
public override void Write(byte[] buffer, int offset, int count) { if (_m_disposed) { throw ADP.ObjectDisposed(this); } _m_fs.Write(buffer, offset, count); // SQLBUVSTS# 193123 - disable lazy flushing of written data in order to prevent // potential exceptions during Close/Finalization. Since System.IO.FileStream will // not allow for a zero byte buffer, we'll create a one byte buffer which, in normal // usage, will cause System.IO.FileStream to utilize the user-supplied buffer and // automatically flush the data directly to the disk cache. In pathological scenarios // where the user is writing a single byte at a time, we'll explicitly call flush ourselves. if (count == 1) { // calling flush here will mimic the internal control flow of System.IO.FileStream _m_fs.Flush(); } }
public static string[] RetrieveAnexosAndWriteToFiles(string username, string password, string timestamp, long limit) { List <string> filenames = new List <string>(); ServicoDocumentos sd = new ServicoDocumentos(); sd.Credentials = new NetworkCredential(username, password); DocumentoInfoArquivoGeral[] diags = sd.ListaDocumentosArquivoGeral(timestamp, limit); foreach (var d in diags) { foreach (var a in d.ARRAYCONTEUDOS.Where(a => a != null)) { ConteudoInfo conteudo = sd.ConsultarAnexoDocumento(d.NUD, a.NOMEFICHEIRO); filenames.Add(conteudo.NOMEFICHEIRO); var stream = new System.IO.FileStream(conteudo.NOMEFICHEIRO, System.IO.FileMode.CreateNew); stream.Write(conteudo.FICHEIRO, 0, conteudo.FICHEIRO.Length); stream.Close(); } } return(filenames.ToArray()); }
/// <summary> /// 下载文件 /// </summary> /// <param name="URL">下载文件地址</param> /// <param name="Filename">下载后的存放地址</param> /// <param name="Prog">用于显示的进度条</param> public static int DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog) { try { System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); long totalBytes = myrp.ContentLength; if (prog != null) { prog.Maximum = (int)totalBytes; } System.IO.Stream st = myrp.GetResponseStream(); System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create); long totalDownloadedByte = 0; byte[] by = new byte[1024]; int osize = st.Read(by, 0, (int)by.Length); while (osize > 0) { totalDownloadedByte = osize + totalDownloadedByte; System.Windows.Forms.Application.DoEvents(); so.Write(by, 0, osize); if (prog != null) { prog.Value = (int)totalDownloadedByte; } osize = st.Read(by, 0, (int)by.Length); } so.Close(); st.Close(); return(1); } catch (System.Exception) { throw; return(0); } }
public static void WriteLog(LogType type, string log) { if (_isInWorkflow) { _stopWatch.Stop(); } StringBuilder _sb = new StringBuilder(); _sb.Append("==========================================================================================="); _sb.Append(DateTime.Now.ToString("HH:mm:ss.fff")); if (_isInWorkflow) { _sb.Append(" |"); _sb.Append(" " + _stopWatch.ElapsedMilliseconds); _sb.Append(" (+" + (_stopWatch.ElapsedMilliseconds - _timeHold) + ")"); _sb.Append(" |"); _sb.Append(" " + _stopWatch.ElapsedTicks); _sb.Append(" (+" + (_stopWatch.ElapsedTicks - _ticksHold) + ")"); } _sb.AppendLine(); _sb.AppendLine(log); string filepath; filepath = Xy.AppSetting.LogDir + type.ToString() + "-" + DateTime.Now.ToString("yyyy-MM-dd") + ".log"; System.IO.FileStream _fs = System.IO.File.Open(filepath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); try { byte[] _log = System.Text.Encoding.UTF8.GetBytes(_sb.ToString()); _fs.Write(_log, 0, _log.Length); _fs.Flush(); } finally { _fs.Close(); } if (_isInWorkflow) { _timeHold = _stopWatch.ElapsedMilliseconds; _ticksHold = _stopWatch.ElapsedTicks; _stopWatch.Start(); } }
public ActionResult NodeCheckin(string id) { if (!System.Text.RegularExpressions.Regex.IsMatch(id, "^[a-zA-Z\\-0-9]+$")) { return(new ContentResult { ContentType = "text/plain", Content = "Bad id" }); } if (Request.Files.Count == 0) { return new ContentResult { Content = "no file", ContentType = "text/plain" } } ; string storepath = Server.MapPath("~/Content/auth/nodes/") + id + ".txt"; var hpf = Request.Files[0] as System.Web.HttpPostedFileBase; using (var fs = new System.IO.FileStream(storepath, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.Read)) { byte[] buffer = new byte[8 * 1024]; int len; while ((len = hpf.InputStream.Read(buffer, 0, buffer.Length)) > 0) { fs.Write(buffer, 0, len); } } //string logPath = Server.MapPath("~/Content/auth/nodes/") + id + System.DateTime.Now.ToString("yyyyMMddHHmm") + ".txt"; //if (!System.IO.File.Exists(logPath)) //{ // System.IO.File.Copy(storepath, logPath); //} return(new ContentResult { Content = "Thanks", ContentType = "text/plain" }); }
/* * 保存为文件 */ void Btn_save_fileClick(object sender, EventArgs e) { string localFilePath = ""; SaveFileDialog sfd = new SaveFileDialog(); //设置文件类型 sfd.Filter = "日志文件(*.log)|*.log"; //设置默认文件类型显示顺序 sfd.FilterIndex = 1; //保存对话框是否记忆上次打开的目录 sfd.RestoreDirectory = true; //点了保存按钮进入 if (sfd.ShowDialog() == DialogResult.OK) { localFilePath = sfd.FileName.ToString(); //获得文件路径 // string fileNameExt =localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1); //获取文件名,不带路径 // System.Diagnostics.Debug.WriteLine(fileNameExt); string aFirstName = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1, (localFilePath.LastIndexOf(".") - localFilePath.LastIndexOf("\\") - 1)); //文件名 // System.Diagnostics.Debug.WriteLine(aFirstName); string aLastName = localFilePath.Substring(localFilePath.LastIndexOf(".") + 1, (localFilePath.Length - localFilePath.LastIndexOf(".") - 1)); //扩展名 // System.Diagnostics.Debug.WriteLine(aLastName); //获取文件路径,不带文件名 string FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\")); //给文件名前加上时间 string newFileName = aFirstName + "[" + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss") + "]" + "." + aLastName; sfd.FileName = FilePath + "\\" + newFileName; try { System.IO.FileStream fs = (System.IO.FileStream)sfd.OpenFile(); //输出文件 //将字符串转成byte数组 byte[] byteFile = Encoding.UTF8.GetBytes(textBox_rec.Text); fs.Write(byteFile, 0, byteFile.Length); fs.Close(); MessageBox.Show("保存成功:" + sfd.FileName); } catch (Exception ex) { MessageBox.Show(ex.Message, "保存文件时发生错误"); return; } } }
public bool DownLoadFile(string URL, string Filename) { try { string msg = Filename; string extension = Path.GetExtension(URL);//扩展名 if (!extension.ToLower().Equals(".jpg")) { msg += "文件名由" + extension + "替换成jpg"; extension = ".jpg"; } System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); //从URL地址得到一个WEB请求 System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); //从WEB请求得到WEB响应 long totalBytes = myrp.ContentLength; //从WEB响应得到总字节数 System.IO.Stream st = myrp.GetResponseStream(); //从WEB请求创建流(读) System.IO.Stream so = new System.IO.FileStream("temp//" + Filename + extension, System.IO.FileMode.Create); //创建文件流(写) long totalDownloadedByte = 0; //下载文件大小 byte[] by = new byte[1024]; int osize = st.Read(by, 0, (int)by.Length); //读流 while (osize > 0) { totalDownloadedByte = osize + totalDownloadedByte; //更新文件大小 Application.DoEvents(); so.Write(by, 0, osize); //写流 osize = st.Read(by, 0, (int)by.Length); //读流 } so.Close(); //关闭流 st.Close(); //关闭流 this.textBox1.Text += msg + Environment.NewLine; return(true); } catch (Exception ex) { Console.WriteLine(ex.Message); return(false); } }
public void DoWork() { foreach (TileInfo info in infos) { try { string filename = string.Format("{0}{1}", info.Index.Col, extension); string filepath = Path.Combine(path, string.Format(@"{0}\{1}\{2}\{3}\", hostname, layername, info.Index.Level, info.Index.Row)); string fullfilename = Path.Combine(filepath, filename); if (!Directory.Exists(filepath)) { Directory.CreateDirectory(filepath); } if (!File.Exists(fullfilename) || !useCache) { try { Byte[] bytes = source.Provider.GetTile(info); System.IO.FileStream stream = new System.IO.FileStream(fullfilename, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); stream.Write(bytes, 0, bytes.Length); stream.Close(); } catch (System.IO.IOException ex) { //if the file is currently donwloaded by a different user it should be available for this package as well ILog log = LogManager.GetLogger("ApplicationLogger"); log.Warn(string.Format("Tile on Path {0} is is being used by another process", fullfilename), ex); } } FilePaths.Add(fullfilename); } catch (Exception ex) { ILog log = LogManager.GetLogger("ApplicationLogger"); log.Error(string.Format("Unknown Error while downloading Tile: Level: {0}; Row: {1}; Column: {2} of Layer: {3}", info.Index.Level, info.Index.Row, info.Index.Col, this.layername), ex); this.Errors.Add(new LoadError(ex, info)); } } }
/// <summary> /// 解码文件 /// </summary> /// <param name="inputFilename">输入文件</param> /// <param name="outputFilename">输出文件</param> /// <param name="encoding">字符编码</param> public static void DecryptFile(string inputFilename, string outputFilename, System.Text.Encoding encoding) { char[] base64CharArray; try { using (System.IO.StreamReader inFile = new System.IO.StreamReader(inputFilename, encoding)) { base64CharArray = new char[inFile.BaseStream.Length]; inFile.Read(base64CharArray, 0, (int)inFile.BaseStream.Length); } } catch { throw; } // 转换Base64 UUEncoded为二进制输出 byte[] binaryData; try { binaryData = System.Convert.FromBase64CharArray(base64CharArray, 0, base64CharArray.Length); } catch { throw; } // 写输出数据 try { using (System.IO.FileStream outFile = new System.IO.FileStream(outputFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { outFile.Write(binaryData, 0, binaryData.Length); } } catch { throw; } }
public byte[] CloseSerialize() { // As the last step, serialize metadata byte[] bytes = SerializeMeta(); AddChecksum(bytes); zip.AddEntry("meta" + jsonExt, bytes); #if !ASTAR_NO_ZIP // Set dummy dates on every file to prevent the binary data to change // for identical settings and graphs. // Prevents the scene from being marked as dirty in the editor // If ASTAR_NO_ZIP is defined this is not relevant since the replacement zip // implementation does not even store dates var dummy = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); foreach (var entry in zip.Entries) { entry.AccessedTime = dummy; entry.CreationTime = dummy; entry.LastModified = dummy; entry.ModifiedTime = dummy; } #endif // Save all entries to a single byte array var output = new MemoryStream(); zip.Save(output); bytes = output.ToArray(); output.Dispose(); #if ASTARDEBUG CompatFileStream fs = new CompatFileStream("output.zip", FileMode.Create); fs.Write(bytes, 0, bytes.Length); fs.Close(); #endif zip.Dispose(); zip = null; return(bytes); }
/// <summary> /// 写入文本 /// </summary> /// <param name="content">文本内容</param> private void Write(string content, string newLine) { if (string.IsNullOrEmpty(_fileName)) { throw new Exception("FileName不能为空!"); } using (System.IO.FileStream fs = new System.IO.FileStream(_fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite, 8, System.IO.FileOptions.Asynchronous)) { Byte[] dataArray = System.Text.Encoding.Default.GetBytes(content + newLine); bool flag = true; long slen = dataArray.Length; long len = 0; while (flag) { try { if (len >= fs.Length) { fs.Lock(len, slen); lockDic[len] = slen; flag = false; } else { len = fs.Length; } } catch (Exception ex) { while (!lockDic.ContainsKey(len)) { len += lockDic[len]; } } } fs.Seek(len, System.IO.SeekOrigin.Begin); fs.Write(dataArray, 0, dataArray.Length); fs.Close(); } }
public static void StaticSave(System.IO.FileStream fs, RingSector[] sectorsArray) { fs.Write(System.BitConverter.GetBytes(sectorsArray.Length), 0, 4); byte zeroByte = 0, oneByte = 1; var gmap = GameMaster.realMaster.globalMap; int info = -1; RingSector s; for (int i = 0; i < sectorsArray.Length; i++) { s = sectorsArray[i]; if (s == null || s.destroyed) { fs.WriteByte(zeroByte); } else { fs.WriteByte(oneByte); fs.Write(System.BitConverter.GetBytes(s.ID), 0, 4); // 0 -3 if (s.centralPoint != null) { info = s.centralPoint.ID; } else { info = -1; } fs.Write(System.BitConverter.GetBytes(info), 0, 4); // 4 - 7 fs.WriteByte((byte)s.environment.presetType); // 8 info = s.innerPointsIDs.Count; fs.Write(System.BitConverter.GetBytes(info), 0, 4); // 9 - 12 if (info > 0) { foreach (var ip in s.innerPointsIDs) { fs.WriteByte(ip.Key); fs.Write(System.BitConverter.GetBytes(ip.Value), 0, 4); } } fs.WriteByte(s.fertile ? oneByte : zeroByte); // 13 } } fs.Write(System.BitConverter.GetBytes(lastFreeID), 0, 4); }
public string GetDatabasePath(string sqliteFilename) { string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); var path = Path.Combine(documentsPath, sqliteFilename); if (!File.Exists(path)) { var dbAssetStream = Forms.Context.Assets.Open(sqliteFilename); var dbFileStream = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate); var buffer = new byte[1024]; int b = buffer.Length; int length; while ((length = dbAssetStream.Read(buffer, 0, b)) > 0) { dbFileStream.Write(buffer, 0, length); } dbFileStream.Flush(); dbFileStream.Close(); dbAssetStream.Close(); } return(path); }
} //public static byte[] LoadBinaryFile( string strFile ) /// <summary> /// 向文件保存二进制数据 /// </summary> /// <param name="strFile">文件名</param> /// <param name="byts">字节数组</param> /// <returns>保存是否成功</returns> public static bool SaveBinaryFile(string strFile, byte[] byts) { try { if (strFile != null) { using (System.IO.FileStream myStream = new System.IO.FileStream( strFile, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { myStream.Write(byts, 0, byts.Length); myStream.Close(); return(true); } } } catch { } return(false); }
public void dump(string filename) { FileStream fs = new FileStream(filename, FileMode.Create); fs.Write(data,0, data.Length); fs.Write(footer, 0, footer.Length); fs.Close(); }